Rails Associations - using data on the association table

为君一笑 提交于 2019-12-11 06:37:46

问题


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,
Mark

Update:

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
  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!

来源:https://stackoverflow.com/questions/6426383/rails-associations-using-data-on-the-association-table

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