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)
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?
答案 0 :(得分:1)
This seems to be the way to go:
def permitted_params
if current_user.admin?
params.require(:organization).permit(:name, :location, :secrets)
else
params.require(:organization).permit(:name, :location)
end
end
Then use permitted_params
in your controller.
答案 1 :(得分:1)
使用以下技术,不需要两次写相同的参数,如果你有很长的属性列表,这会很有用。
def organization_params
attributes = [:name, :location]
attributes.push(:secrets) if current_user.admin?
params.require(:organization).permit(attributes)
end
答案 2 :(得分:0)
你应该做的很简单:
def organization_params
basic_filter = %w(name location)
filter = user.admin? ? basic_filter.push('secrets') : basic_filter
params.require(:organization).permit(filter)
end
这将按你看到的那样工作:
[20] pry(main)> params = ActionController::Parameters.new({
[20] pry(main)* organization: {
[20] pry(main)* name: 'Francesco',
[20] pry(main)* location: 'L.A.',
[20] pry(main)* secrets: 'secrets'
[20] pry(main)* }
[20] pry(main)* })
=> {"organization"=>{"name"=>"Francesco", "location"=>"L.A.", "secrets"=>"secrets"}}
[21] pry(main)> basic_filter = %w(name location)
=> ["name", "location"]
[22] pry(main)> filter = true ? basic_filter.push('secrets') : basic_filter
=> ["name", "location", "secrets"]
[23] pry(main)> params.require(:organization).permit(filter)
=> {"name"=>"Francesco", "location"=>"L.A.", "secrets"=>"secrets"}
如果user.admin?
false ,则结果为
[26] pry(main)> basic_filter
=> ["name", "location", "secrets"]
[27] pry(main)> basic_filter = %w(name location)
=> ["name", "location"]
[28] pry(main)> filter = false ? basic_filter.push('secrets') : basic_filter
=> ["name", "location"]
[29] pry(main)> params.require(:organization).permit(filter)
Unpermitted parameter: secrets
=> {"name"=>"Francesco", "location"=>"L.A."}
这可能会对你有帮助。