我有一个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
这是我的用户控制器中更新方法的样子:
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
我在应用控制器中有一个辅助方法,它以字符串形式返回角色:
def current_user_role
@current_user_role ||= current_user.admin? ? "admin" : "default"
end
helper_method :current_user_role
我还在
config/application.rb
中设置了config.active_record.whitelist_attributes = true
。我已验证
current_user_role
方法根据当前用户的管理员状态返回正确的值。Rails没有抛出批量赋值错误。但是,当我尝试以管理员身份登录并更新用户的管理员状态时,Rails会执行更新操作,并静默忽略admin
属性。在Rails控制台中查看用户记录显示记录未被修改。我感觉这可能是一个我不知道的Ruby或Rails特定问题。我找不到有关使角色动态的任何信息。我能找到的最好的是这个。