2012-09-13 69 views
0

我再次陷入一個簡單的查詢。我有以下型號帶條件的多個連接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) 

它其中包含的條件時,拋出了我的錯誤。我不知道爲什麼會這樣做。我認爲這是一個非常基本的聯合,我可以自己做,但徒勞無功。

+1

,你能否告訴我們錯誤信息? – MurifoX

回答

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 
+0

nick當我使用@ category.items進行查詢時,我正在獲取item_types。結果查詢如下所示:SELECT「categories」。* FROM「categories」INNER JOIN「item_types」ON「categories 」。「id」=「item_types」 。「category_id」WHERE「item_types」。「category_id」= 1 – Ramoji

+0

你完全改變了我的要求。我有三種模式:Category,ItemType和Item.A Category可以有許多itemtypes和許多itemtype.A ItemType屬於一個category並有很多項目。一個項目屬於一個ItemType ..這是我模仿我的問題。 – Ramoji

0
Category.joins(:item_types,:items).where("**categories**.id=?",1) 

表名稱應該是在where子句

+0

我可否知道拒絕投票的原因.. – Rubyman

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

我的商品表沒有category_id列 – Ramoji

+0

對於此錯字感到抱歉 – st8998