Nic*_*nil 7 ruby-on-rails strong-parameters
我不想根据当前用户的角色允许某些参数.
例如:role如果用户是管理员,则仅允许该属性.
这可能吗?
Fre*_*rin 24
是的,这是可能的.
你可以这样做:
def user_params
# List of common params
list_params_allowed = [:email, :title, :last_name, :first_name, :phone]
# Add the params only for admin
list_params_allowed << :role if current_user.admin?
params.require(:user).permit(list_params_allowed)
end
Run Code Online (Sandbox Code Playgroud)
这样,如果以后你有新的参数,你只需要添加一个列表(避免错误).
如果要为管理员添加多个参数,可以这样执行:
list_params_allowed << :role << other_param << another_param if current_user.admin?
Run Code Online (Sandbox Code Playgroud)
希望这有帮助.