Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access the joining model on a has_many :through relationship
    text
    copied!<p>I have a typical many-to-many relationship using <code>has_many =&gt; :through</code>, as detailed below.</p> <pre><code>class member has_many member_roles has_many roles, :through =&gt; :member_roles end class role has_many member_roles has_man members, :through =&gt; :member_roles end class member_role belongs_to :member belongs_to :role # has following fields: member_id, role_id, scope, sport_id end </code></pre> <p>What I'm trying to do here is allow members to be assigned roles. Each member role has a scope, which by default is set to "All" but if desired can be set to "Sport". If the scope is set to sport then we also capture the sport_id, which allows us to restrict assess on that role to a particular sport (ie, can only manage the teams of that sport, rather than the teams of every sport). Sounds simple enough.</p> <p>I have setup my <code>update_member_roles</code> action something like this:</p> <pre><code>def update # Assume we passing a param like: params[:member][:roles] # as an array of hashes consisting of :role_id and if set, :sport_id roles = (params[:member] ||= {}).delete "roles" @member.roles = Role.find_all_by_id(roles.map{|r| r["role_id"]}) if @member.update_attributes params[:member] flash[:notice] = "Roles successfully updated." redirect_to member_path(@member) else render :action =&gt; "edit" end end </code></pre> <p>The above works nice enough, it sets the appropriate member_roles very nicely... but as I'm working on the Role model and not the MemberRole model I'm kind of stuck as to how I can access the joining model to set the :scope and :sport_id.</p> <p>Any pointers here would be much appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload