Rails Associations - using data on the association table
I've got a question about associations in Rails 2.3.11
I have two models:
- Activities
- Organisations
they have a has_and_belongs_to_many
relationship. But they also have an important and per-activity-organisation relationship type
. They are connected together via the activities_organisations
table, which has three columns:
- activity_id
- organisation_id
- rel_type
The rel_type
can be set as 1
(funding), 2
(extending) or 3
(implementing).
The association works fine and I can call @activity.organisations
or @organisation.activities
. But I'd also like to call this depending on the rel_type
- so that I can for example call only an activity's implementing organisation (where rel_type == 3
)
At the moment I have this (on the Organisations / index view), but I think there must be a nicer way?
<%
@conditions = {}
@conditions[:organisation_id] = organisation.id
@reltype = ActivitiesOrganisation.all(:conditions=>@conditions, :group=>:rel_type)%>
<td><% @reltype.each do |r| %><%= r.rel_type %><% end %></td>
</tr>
<% end %>
<% end %>
I found this but I got stuck trying to include it in my models, and I'm not sure how much of it applies.
Would be extremely grateful for any help!
Thanks,
MarkUpdate:
Thanks to @ghoppe in the comments, I realised I was being a bit of an idiot... This is my code now:
Activity Model
class Activity < ActiveRecord::Base
has_many :activity_organisations
开发者_C百科has_many :funding_activity_organisations, :class_name => "ActivitiesOrganisation",
:conditions => {:rel_type => 1}
has_many :extending_activity_organisations, :class_name => "ActivitiesOrganisation",
:conditions => {:rel_type => 2}
has_many :implementing_activity_organisations, :class_name => "ActivitiesOrganisation",
:conditions => {:rel_type => 3}
has_many :organisations, :through => :activity_organisations
has_many :funding_organisations, :through => :funding_activity_organisations, :source => :organisation
has_many :extending_organisations,:through => :extending_activity_organisations,:source => :organisation
has_many :implementing_organisations,:through => :implementing_activity_organisations,:source => :organisation
end
ActivitiesOrganisation Model
class ActivitiesOrganisation < ActiveRecord::Base
belongs_to :activity
belongs_to :organisation
end
Thanks!
精彩评论