2011-12-10 9 views
0

私のRails 3アプリには、ProfileItemという2つのモデルがあります。それぞれは、他とHABTM関係を持っています。私のプロファイルモデルでは、同じ名前(wish_items)の配列を作成するメソッドwish_itemsがあります。アイテムにカテゴリ「wish」が含まれている場合は、そのプロファイルのwish_itemsアレイに追加されます。オブジェクト名がHABTMの関係を持つすべてのプロファイルを見つけて計測する

この質問の目的のために、カテゴリ「wish」の「phone」という項目があります。私がしたいのは、wish_items配列内に「電話」を持つすべてのプロファイルを見つけて数えることができるので、その数をビューでレンダリングすることができます。私のコードは以下の通りです。

マイProfile.rbモデル:

class Profile < ActiveRecord::Base 
    has_and_belongs_to_many :items 

    def wish_items 
    wish_items = Array.new 
    items.each do |item| 
     if item.category == "wish" 
     wish_items << item 
     end 
    end 
    return wish_items 
    end 
end 

マイItem.rbモデル:

class Item < ActiveRecord::Base 
    has_and_belongs_to_many :profiles 
end 

私はこの関係を表items_profilesに参加しています。ここではその移行は次のとおりです。

class CreateItemsProfiles < ActiveRecord::Migration 
    def self.up 
    create_table :items_profiles, :id =>false do |t| 
     t.references :item 
     t.references :profile 
    end 
    end 
... 
end 

私はこのprevious questionを見て、答えを試しましたが、エラーNameError: uninitialized constant phoneを得ました。ここで私はそれから試したコードは次のとおりです。

Profile.all(:include => :items, :conditions => ["items.name = ?", phone]) 

具体的に私は、次の中でそのコードを置く:

<%= pluralize(Profile.all(:include => :items, :conditions => ["items.name = ?", phone])).count, "person") %> 

私はこれをどのように行うことができますか?

答えて

0

私は引用符で電話を持っていなかったので上記は失敗していました。シンプル。以下は、働いていた:

Profile.all(:include => :items, :conditions => ["items.name = ?", "phone"]) 

と複数形:

<%= pluralize(Profile.all(:include => :items, :conditions => ["items.name = ?", "phone"]).count, "person") %> 
関連する問題