Help with a Join in Rails 3

こ雲淡風輕ζ 提交于 2020-01-02 07:13:18

问题


I have the following models:

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

And what I want to do is, for a given event, find all the action items that have an action item type with a name of "foo" (for example). So I think the SQL would go something like this:

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"

Can anybody help me translate this into a nice active record query? (Rails 3 - Arel)

Thanks!


回答1:


Well I think I solved it myself. Here's what I did

e = Event.find(1)
e.action_items.joins(:action_item_type).where("action_item_types.name = ?", "foo")



回答2:


Ehm, why not define

has_many :action_item_types, :through => :action_items

and refer to

e.action_item_types.where(:name => "foo")

?




回答3:


or (as long as "name" is a unique column name)

e.action_items.joins(:action_item_type).where(:name => "foo")


来源:https://stackoverflow.com/questions/4280315/help-with-a-join-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!