0

私は再び単純なクエリで立ち往生しています。私は次のモデルを持っています

class Category < ActiveRecord::Base
  has_many :item_types
  has_many :items, :through => :item_types, :source => :category    
end

class ItemType < ActiveRecord::Base
  belongs_to :category
  has_many :items 
end

class Item
  belongs_to :item_type
end

現在、カテゴリに分類されるすべてのアイテムをフェッチするクエリを作成しようとしています。私はこのようなクエリを書きました:

Category.joins(:item_types,:items).where("category.id=?",1)

where条件が含まれているとエラーが発生します。なぜそうなるのかわかりません。これは非常に基本的な参加だと思いましたが、自分でやることはできましたが、無駄でした。

4

3 に答える 3

2
Category.joins(:item_types, :items).where(:item_type => {:category_id => 1})
于 2012-09-14T11:50:48.813 に答える
0
Category.joins(:item_types,:items).where("**categories**.id=?",1)

カテゴリのテーブル名はwhere句に含める必要があります

于 2012-09-13T13:31:16.600 に答える
0

ActiveRecord との多対多の関連付けを構築したい場合は、はるかに簡単です。私があなたの質問を明確に理解しているなら、あなたはこのようなことをすべきです

# app/models/category.rb
class Category < ActiveRecord::Base
  has_many :item_types
  has_many :items, :through => :item_types
end

# app/models/item_type.rb
class ItemType < ActiveRecord::Base
  belongs_to :category
  belongs_to :item
end

# app/models/item.rb
class Item < ActiveRecord::Base
  has_many :item_types
  has_many :categories, :through => :item_types
end

# app/controllers/categories_controller.rb
def show
  @category = Category.find(params[:id])
  @category_items = @category.items
end
于 2012-09-13T13:27:51.327 に答える