帮助加入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")