Ruby on rails 3 Rails 3.2-接受和连接模型的嵌套属性

Ruby on rails 3 Rails 3.2-接受和连接模型的嵌套属性,ruby-on-rails-3,has-many-through,nested-attributes,Ruby On Rails 3,Has Many Through,Nested Attributes,我有以下模型:用户,角色,用户角色(用户角色是一种加入模型) 我试图使用“用户编辑”页面上的复选框编辑用户的角色。这是我的尝试,我觉得我错过了一些重要的东西,或者采取了错误的方法 user.rb 用户角色.rb role.rb 用户\u controller.rb users/edit.html.haml 这是我的解决办法。我从学校得到了很多帮助。按照复选框的设置方式,如果“未选中”,它将销毁UserRole,并且仅在“选中”时创建它(为什么“0”、“1”在该行上) 用户\u controlle

我有以下模型:
用户
角色
用户角色
用户角色
是一种加入模型)

我试图使用“用户编辑”页面上的复选框编辑用户的角色。这是我的尝试,我觉得我错过了一些重要的东西,或者采取了错误的方法

user.rb 用户角色.rb role.rb 用户\u controller.rb users/edit.html.haml
这是我的解决办法。我从学校得到了很多帮助。按照复选框的设置方式,如果“未选中”,它将销毁UserRole,并且仅在“选中”时创建它(为什么“0”、“1”在该行上)

用户\u controller.rb user.rb users/edit.html.haml
has_many :user_roles, dependent: :destroy
has_many :roles, through: :user_roles

attr_accessible :user_roles_attributes

accepts_nested_attributes_for :user_roles, reject_if: lambda { |a| a[:role_id] == 0 }, allow_destroy: true

def has_role?(role_sym)
  roles.any? { |r| r.name.underscore.to_sym == role_sym.downcase }
end

def setup_roles!
  Role.all.each { |role|
    user_roles.build(user_id: id, role_id: role.id) unless has_role?(role.name.to_sym)
  }
end
belongs_to :user
belongs_to :role
delegate :name, to: :role
has_many :user_roles
has_many :users, through: :user_role
def edit
  @user = User.find(params[:id])
  @user.setup_roles!
end

def update
  @user = User.find(params[:id])
  if @user.update_attributes(params[:user])
    flash[:notice] = 'User was successfully updated.'
    redirect_to edit_user_path(@user)
  else
    render :edit
  end
end
= form_for @user do |f|
  = f.fields_for(:user_roles) do |role_form|
    = role_form.check_box :role_id, {}, role_form.object.role_id, 0
    = role_form.hidden_field :user_id
    = role_form.label :name, role_form.object.name

  = f.submit 'Update'
def edit
  @user = User.find(params[:id])
  @user.setup_roles!
end
def has_role?(role_sym)
  roles.any? { |r| r.name.underscore.to_sym == role_sym.downcase }
end

def setup_roles!
  Role.all.each { |role|
    user_roles.build(role: role) unless has_role?(role.name.to_sym)
  }
end
= form_for @user do |f|                                                            
  = f.fields_for :user_roles do |builder|                                          
    = builder.check_box :_destroy, { checked: builder.object.persisted? }, '0', '1'
    = builder.label :_destroy, builder.object.role.name                            
    = builder.hidden_field :role_id                                                

  = f.submit 'Update'