Ruby on Rails的:包括与子模型多态关联
题
当用多态关联的工作,是有可能运行包括关于仅在某些类型的本子模型?
示例:
class Container
belongs_to :contents, :polymorphic => true
end
class Food
has_one :container
belongs_to :expiration
end
class Things
has_one :container
end
在认为我会想要做的事,如:
<% c = Containers.all %>
<% if c.class == Food %>
<%= food.expiration %>
<% end %>
所以,我想急于负载到期时,我加载了C,因为我知道我需要他们每个最后一个。有没有办法这样做呢?只是定义正:包括让我的错误,因为不是所有的封闭式类型都有一个子模型到期
解决方案
<强>被修改应答强>
我最近发现的Rails支持多态关联的急切装载时通过多态型柱进行过滤。所以,没有必要申报虚假关联。
class Container
belongs_to :content, :polymorphic => true
end
现在通过Container
查询container_type
。
containers_with_food = Container.find_all_by_content_type("Food",
:include => :content)
containers_with_thing = Container.find_all_by_content_type("Thing",
:include => :content)
<强>旧应答强>
这是一个黑客,因为没有直接的方法来包括在一个查询中的多态型的对象。
class Container
belongs_to :contents, :polymorphic => true
# add dummy associations for all the contents.
# this association should not be used directly
belongs_to :food
belongs_to :thing
end
现在通过Container
查询container_type
。
containers_with_food = Container.find_all_by_content_type("Food",
:include => :food)
containers_with_thing = Container.find_all_by_content_type("Thing",
:include => :thing)
这导致两个SQL调用数据库(实际上它是4级的呼叫作为轨道执行一个SQL每:include
)
有没有办法,因为你需要为不同的内容类型不同的列设置为此在一个SQL。
<强>警告:在Content
类虚设协会不应该直接使用,因为它会导致意想不到的结果
E.g:可以说在contents
表中的第一对象包含食品
Content.first.food # will work
Content.first.thing
在第二呼叫将不工作。作为Thing
对象指向的Food
它可能给你一个Content
对象具有相同ID。
不隶属于 StackOverflow