Ruby on rails 3 如何通过关联对所属对象进行建模
我有三个模型类别,ItemType和Item。用简单的英语,我可以把我的要求说成:一个类别可以有零个或多个ItemType。ItemType只能属于一个类别,并且可以有零个或多个项目。一个项目通过ItemType属于一个ItemType和一个类别。我将它们关联如下:Ruby on rails 3 如何通过关联对所属对象进行建模,ruby-on-rails-3,activerecord,Ruby On Rails 3,Activerecord,我有三个模型类别,ItemType和Item。用简单的英语,我可以把我的要求说成:一个类别可以有零个或多个ItemType。ItemType只能属于一个类别,并且可以有零个或多个项目。一个项目通过ItemType属于一个ItemType和一个类别。我将它们关联如下: class Category < ActiveRecord::Base has_many :item_types has_many :items ,:through => item_types, :sour
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
我得到下面的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)
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
有人能帮我吗?如何获得下面的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)
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
我不确定我会在这里依赖rails魔术。你能试试吗
Category.includes([:item_types,:items]).where(['items.item_type_id = ?',categories.item_type.id]).where(<...your conditions...>)
Category.includes([:item_type,:items])。其中(['items.item_type_id=?',categories.item_type.id])。其中()
很抱歉,在发布之前没有时间亲自检查:-(如果我是正确的,则关联声明不完整。您可能需要在ItemType&Item model中添加
属于: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
像这样的东西应该有用
#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
class ItemType
这里是一个相关链接-。您可能会在这里获得更多详细信息。打字?:through=>subcategories“没有其他意义。对于“join(:business\u types,:businesss)”@Atastor,我已经尝试更改原始名称。现在我已经确保它在所有地方都是一致的