帮助加入Rails 3

Ada*_*cht 3 activerecord join ruby-on-rails ruby-on-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
Run Code Online (Sandbox Code Playgroud)

而我想要做的是,对于给定的事件,找到具有名称为"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"
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我翻译成一个很好的活动记录查询吗?(Rails 3 - Arel)

谢谢!

Ada*_*cht 8

好吧,我想我自己解决了.这就是我做的

e = Event.find(1)
e.action_items.joins(:action_item_type).where("action_item_types.name = ?", "foo")
Run Code Online (Sandbox Code Playgroud)

  • 如果你想让它更好看,你可以做`e.action_items.joins(:action_item_type).where(:action_item_types => {:name =>"foo"})` (9认同)