【问题标题】:Rails 3.2 - accepts_nested_attributes_for and join modelsRails 3.2 - 接受_nested_attributes_for 并加入模型
【发布时间】:2012-02-10 05:56:01
【问题描述】:

我有以下模型:userroleuser_roleuser_role 是连接模型)

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

user.rb

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

user_role.rb

belongs_to :user
belongs_to :role
delegate :name, to: :role

角色.rb

has_many :user_roles
has_many :users, through: :user_role

users_controller.rb

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

用户/edit.html.haml

= 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'

【问题讨论】:

    标签: ruby-on-rails-3 has-many-through nested-attributes


    【解决方案1】:

    这是我的解决方案。我从This Post at RubySource 那里得到了很多帮助。复选框的设置方式,如果“未选中”,它将破坏 UserRole,并且仅在“选中”时创建它(为什么'0','1'在那一行。)

    users_controller.rb

    def edit
      @user = User.find(params[:id])
      @user.setup_roles!
    end
    

    user.rb

    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
    

    用户/edit.html.haml

    = 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'                                                              
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 2013-12-24
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多