使用相关模型属性返回对象
问题描述:
我有一个对象Item
可以是ItemType
之一。该ItemType
有一个attribute
这是true
或false
。使用相关模型属性返回对象
Class Item
belongs_to :item_type
end
Class ItemType
has_many :items
end
目前,我只是抓住以通常的方式最后x
对象:
latest_items = Item.last(x)
现在,我需要返回的x
Items
一个列表,其中ItemType
有attribute
设为true
,像这样(伪):
latest_items = Item.last(x).where(Item.item_type.attribute = "true")
这是R中很容易实现苦恼的?现在看来似乎应该是简单的,但我四处摸索,无法找到解决方案
答
您可以通过使用
latest_items = Item.joins(:item_type).where("item_type.attribute = ?", true).limit(x).order('id desc')
完美工作很容易做到这一点 - 非常感谢 – 2013-02-24 20:53:55
不客气: ) – 2013-02-24 20:54:32