我如何使用form_for来更新关联的has_many:通过关联

时间:2011-03-15 17:48:02

标签: ruby-on-rails form-for nested-form-for

在我的member_profile表单中,我想拥有对管理员可见的角色复选框。我想使用一些嵌套的form_for,但不能使它工作,所以我使用手动创建check_box_tags(见下文),然后手动将它们添加到member_profile.member。

请注意,成员模型是Devise,我不希望将这些字段与我的MemberProfile数据混合,以防我将来更改auth系统。

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

表格(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

1 个答案:

答案 0 :(得分:0)

我认为只做一个嵌套的has_many:通过更新是有意义的,因为连接模型正在“通过”到达has_many:through模型。在创建hmt之前,连接模型中显然没有记录。