强参数:如何使用条件允许参数

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)

希望这有帮助.

  • `list_params_allowed + = [:role]如果current_user.admin?听起来更好,尤其是如果您以后可能想添加更多参数的话。 (2认同)
  • 是的,但是在 1 个元素的情况下,`allowed_pa​​rams &lt;&lt; :role` 看起来比 `allowed_pa​​rams += [:role]` 更清晰。在任何情况下,这样的结构都很容易重构。 (2认同)