在 Rails 4 中使用强参数允许特殊情况下的额外参数 [英] Permit extra params in special cases with Strong Params in Rails 4

查看:59
本文介绍了在 Rails 4 中使用强参数允许特殊情况下的额外参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于组织而言,我希望用户能够对其进行编辑.

So for an organization, I want users to be able to be able to edit some things about it.

params.require(:organization).permit(:name, :location)

但在特殊情况下,我希望管理员能够编辑额外的属性

But in special cases, I want administrators to be able to edit extra attributes

params.require(:organization).permit(:name, :location, :secrets)

现在我知道我可以只用一个 if 语句来选择我想要使用的那一行,但是由于管理员将始终能够编辑原始属性,我希望能够像这样轻松地包含它们:

Now I know I can just have an if statement to choose which line I want to use, but since the admin will always be able to edit the original attributes, I wanted to easily be able to include them like so:

permitted = params.require(:organization).permit(:name, :location)
permitted.permit(:secrets) if current_user.admin?

有没有办法链接这样的许可调用?或者我是否必须执行一些操作,例如将属性存储在数组中并在发出许可调用之前有条件地添加额外内容?

Is there any way to chain permit calls like that? Or do I have to do something like store the attributes in an array and conditionally add extra before making the permit call?

推荐答案

使用下面的技术,不需要写两次相同的参数,如果你有很长的属性列表,这很有帮助.

Using the below technique, there's no need to write the same params twice, which is helpful if you have a long list of attributes.

def organization_params
  attributes = [:name, :location]
  attributes.push(:secrets) if current_user.admin?

  params.require(:organization).permit(attributes)
end

这篇关于在 Rails 4 中使用强参数允许特殊情况下的额外参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆