2012-09-14 81 views
0

我有三個模型類別,ItemType和Item.In純英文我可以把我的要求爲:一個類別可以有零個或多個itemtypes.A ItemType只能屬於一個類別,並且可以零個或多個items.An項目屬於一個項目類型和通的itemtype.i've有關它們如下類別:如何通過關聯模型belongs_to

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

現在,我怎麼一個項目有category.One我的觀點需要關聯顯示一個類別的所有項目。 當我查詢它作爲

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

我得到下面的SQL

SELECT "categories".* FROM "categories" INNER JOIN "item_types" ON "item_t 
    ypes"."category_id" = "categories"."id" INNER JOIN "item_types" 
    "item_types_categories_join" ON "item_types_categories_join"."category_id" = 
    "categories"."id" INNER JOIN "categories" "items_categor 
    ies" ON "items_categories"."id" = "item_types_categories_join"."category_id" WHERE 
    (categories.id=1) 

誰能幫我出here.How得到下面的SQL

select * from categories 
     inner join item_type on categories.id=item_types.category_id 
     inner join items on item_types.id=items.item_type_id 
where categories.id =1 
+0

錯字? 「:through =>子類別」否則無意義。 – Atastor

+0

同樣的「聯合(:business_types,:企業)」 – Atastor

+0

@Atastor我試過改變原來的名字..現在我已經確保它的一貫到處 – Ramoji

回答

0

我不知道我在這裏依靠鐵軌魔術。你可以嘗試

Category.includes([:item_types,:items]).where(['items.item_type_id = ?',categories.item_type.id]).where(<...your conditions...>) 

對不起,我沒有時間張貼:-(

1

如果我是正確的,該協會聲明不完整之前檢查它自己。你可能需要在ItemType的&項目模型添加belongs_to :category例如:

class Category < ActiveRecord::Base 
    has_many :item_types 
    has_many :items ,:through => item_types 
end 
class ItemType < ActiveRecord::Base 
    has_many :items 
    belongs_to :category 
end 
class Item < ActiveRecord::Base 
    belongs_to :item_type 
    belongs_to :category 
end 

現在類的實例應該能夠列出所有的項目,如你想列出一個類別的所有項目,你應該得到它:

cat = Category.find_by_id(ID_GOES_HERE) 
cat.items 
1

像這樣的東西應該工作

#this will load your item_types and items earlier with less query. 
Category.find(1, :include => [:item_types, :items]) 

而且你的模型需要以下變化

class ItemType < ActiveRecord::Base 
... ... 
+ belongs_to :category 
end 

class Item < ActiveRecord::Base 
... ... 
+ belongs_to :category 
end 

這裏是一個相關鏈接 - Rails Active Record: find in conjunction with :order and :group。你可能會在這裏獲得更多細節。

相關問題