符合轨道3.2.7条件的多个接头



我又被一个简单的查询卡住了。我有以下型号的

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)

当包含条件时,它给我带来了一个错误。我不知道它为什么会那样。我认为这是一个非常基本的加入,我可以自己做,但徒劳。

Category.joins(:item_types, :items).where(:item_type => {:category_id => 1})

如果您想使用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
Category.joins(:item_types,:items).where("**categories**.id=?",1)

类别的表名应在where子句中

最新更新