Rails has_many :through Find by Extra Attributes in Join Model Rails has_many :through Find by Extra Attributes in Join Model ruby ruby

Rails has_many :through Find by Extra Attributes in Join Model


How about adding something like this into your User model?

has_many  :active_events, :through => :event_users,           :class_name => "Event",           :source => :event,           :conditions => ['event_users.active = ?',true]

After that you should be able to get active events for a user just by calling:

User.first.active_events


Milan Novota has a good solution – but :conditions is now deprecated and the :conditions => ['event_users.active = ?',true] bit just doesn't seem very rails anyways. I prefer something like this:

has_many :event_usershas_many :active_event_users, -> { where active: true }, class_name: 'EventUser'has_many :active_events, :through => :active_event_users, class_name: 'Event', :source => :event

After that you should still be able to get active events for a user just by calling:

User.first.active_events


Even though your u.events isn't explicitly calling the user_events table, that table is still included in the SQL implicitly because of the necessary joins. So, you can still use that table in your find conditions:

u.events.find(:all, :conditions => ["user_events.active = ?", true])

Of course, if you plan to be doing this lookup a lot then sure, give it a separate association as Milan Novota suggests, but there's no requirement for you to do it that way