如何通过关联建立belongs_to模型

时间:2012-09-14 07:17:03

标签: ruby-on-rails-3 activerecord

我有三个模型Category,ItemType和Item。简单来说,我可以将我的要求设为:一个类别可以有零个或多个项类型。一个ItemType必须只属于一个类别,并且可以有零个或多个项目。一个项目属于一个项目类型,一个类别通过itemtype.i将它们关联起来如下:

 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.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)

任何人都可以帮助我。如何获得以下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

3 个答案:

答案 0 :(得分:1)

如果我是正确的,则关联声明不完整。您可能需要在ItemType&amp;中添加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 :(得分: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。您可以在此处获得更多详细信息。

答案 2 :(得分:0)

我不确定我会在这里依赖rails魔法。你能试试吗

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

很抱歉在发布之前没有时间自己检查: - (