我使用Rails(3.2.3)和Devise,并允许管理员创建新用户 - 并编辑用户帐户。
此时,管理员可以成功创建帐户。但是,他们无法对其进行编辑。
当您尝试编辑用户的帐户时,会引发质量分配错误:
Can't mass-assign protected attributes: email, name
即使在User模型中,这些属性也设置为可访问:
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
有趣的是,如果我将上述行更改为attr_protected
,您可以编辑用户信息,但不能再创建用户了。非常奇怪。
以下是我正在使用的相关代码......感谢任何帮助。
用户模型:
class User < ActiveRecord::Base
rolify
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :role_ids, :as => :admin
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
end
用户控制器:
class UsersController < ApplicationController
before_filter :authenticate_user!
def update
authorize! :update, @user, :message => 'Not authorized as an administrator.'
@user = User.find(params[:id])
if params[:user][:password].blank?
params[:user].delete(:password)
params[:user].delete(:password_confirmation)
end
if @user.update_attributes(params[:user], :as => :admin)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
def edit
@user = User.find(params[:id])
end
def create
@user = User.new(params[:user])
if params[:user][:password].blank?
params[:user].delete(:password)
params[:user].delete(:password_confirmation)
end
respond_to do |format|
if @user.save
format.html { redirect_to users_path, notice: 'User was successfully created.' }
else
format.html { render action: "new" }
end
end
end
end
答案 0 :(得分:1)
更改为
class User < ActiveRecord::Base
rolify
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :role_ids, :name, :email, :password, :password_confirmation, :remember_me, :as => :admin
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
end
现在管理员可以成功创建帐户&amp;他们 CAN 也可以编辑它们。希望它有所帮助