[英]Multiple joins with conditions in rails 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子句中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.