Help Connecting to Rails 3

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 I want for this event to find all action elements that have the action element type named "foo" (for example). Therefore, I think SQL will look 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 someone help me translate this into a nice active write request? (Rails 3 - Arel)

Thank!

+3
source share
3 answers

Well, I think I decided it myself. Here is what i did

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

Ehm why not define

has_many :action_item_types, :through => :action_items

and refer to

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

?

+4
source

( , "" )

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

All Articles