Search code examples
ruby-on-railsruby-on-rails-4strong-parameters

Permit extra params in special cases with Strong Params in 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)

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?


Solution

  • 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