[英]Help with a Join in Rails 3
我有以下型号:
class Event < ActiveRecord::Base
has_many :action_items
end
class ActionItem < ActiveRecord::Base
belongs_to :event
belongs_to :action_item_type
end
class ActionItemType < ActiveRecord::Base
has_many :action_items
end
我想要做的是,对于给定的事件,找到具有名称为“foo”的动作项类型的所有动作项(例如)。 所以我认为SQL会像这样:
SELECT * FROM action_items a
INNER JOIN action_item_types t
ON a.action_item_type_id = t.id
WHERE a.event_id = 1
AND t.name = "foo"
任何人都可以帮我翻译成一个很好的活动记录查询吗? (Rails 3 - Arel)
谢谢!
好吧,我想我自己解决了。 这就是我做的
e = Event.find(1)
e.action_items.joins(:action_item_type).where("action_item_types.name = ?", "foo")
嗯,为什么不定义
has_many :action_item_types, :through => :action_items
并参考
e.action_item_types.where(:name => "foo")
?
或(只要“name”是唯一的列名)
e.action_items.joins(:action_item_type).where(:name => "foo")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.