Search code examples
ruby-on-railsform-fornested-form-for

How can I use form_for to update an association's has_many :through association


In my form for member_profile, I would like to have role checkboxes that are visible for admins. I would like to used some nested form_for, but can't make it work, so I've resorted to manually creating the check_box_tags (see below), and then manually adding them to member_profile.member.

Note that the Member model is Devise, and I don't want to mix those fields in with my MemberProfile data, in case I change auth systems in the future.

class Member < ActiveRecord::Base
  has_one :member_profile
  has_many :member_roles
  has_many :roles, :through => :member_roles
end
class MemberProfile < ActiveRecord::Base
  belongs_to  :member
  has_many    :member_roles, :through => :member
  #has_many    :roles, :through => :member_roles #can't make this work work
end
class Role < ActiveRecord::Base
  has_many :member_roles
  validates_presence_of :name
end
class MemberRole < ActiveRecord::Base
  belongs_to :member
  belongs_to :role
end

Form (haml)

  = form_section do
    - Role.all.each do |x|

      =check_box_tag  'member[role_ids][]', 
                      x.id, 
                      begin @resource.member.role_ids.include?(x.id) rescue nil end
      =x.name

member_profiles_controller.rb

def update
  if @resource.update_attributes params[:member_profile]

    @resource.member.role_ids = params[:member][:role_ids]
    redirect_to(@resource, :notice => 'Member profile was successfully updated.') 
  else
    render :action => "edit" 
  end
end

Solution

  • I've decided it only makes sense to do a nested has_many :through on Update, since the join model is what is being 'gone through' to get to the has_many :through model. Before the hmt is created, there is obviously no record in the join model.