我有一个Rails应用程序,其中包含一个包含admin属性的用户模型.它已被锁定使用attr_accessible.我的模型看起来像这样:
attr_accessible :name, :email, :other_email, :plant_id, :password, :password_confirmation
attr_accessible :name, :email, :other_email, :plant_id, :password, :password_confirmation, :admin, :as => :admin
Run Code Online (Sandbox Code Playgroud)
以下是我的用户控制器中的更新方法:
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user], :as => current_user_role.to_sym)
flash[:notice] = "Profile updated"
redirect_to edit_user_url(@user)
else
render 'edit'
end
end
Run Code Online (Sandbox Code Playgroud)
我的应用程序控制器中有一个帮助方法,它将角色作为字符串传回:
def current_user_role
@current_user_role ||= current_user.admin? ? "admin" : "default"
end
helper_method :current_user_role
Run Code Online (Sandbox Code Playgroud)
我也开始config.active_record.whitelist_attributes = true了config/application.rb.
我已经验证该current_user_role方法是根据当前用户的管理状态返回正确的值.Rails没有抛出质量分配错误.但是当我以管理员身份登录时尝试更新用户的管理状态时,Rails会执行更新并默默忽略该admin属性.在Rails控制台中拉出用户的记录表明该记录尚未被修改.
我觉得有一个特定于Ruby或Rails的问题,我不知道.我无法找到有关使角色动态化的任何信息.我能找到的最好的就是这个.