Search code examples
ruby-on-railsstrong-parameters

Shortcut for including strong parameters in Rails 4 : without listing all fields


I am starting with Rails 4. Had came across to the new security feature strong parameters related to permitting parameter in a controller.

http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

This is fine, but we need to list down all the fields from the models. Is there a easy way by which listing fields down the is not required.

Thanks.


Solution

  • Strong Parameters were introduced in Rails 4:

    It provides an interface for protecting attributes from end-user assignment. This makes Action Controller parameters forbidden to be used in Active Model mass assignment until they have been whitelisted.

    Basically, it means only certain param values will be sent through your controller to the model (thus allowing you more control over which data is handled by Rails)


    DRY

    If you're wanting to use strong params for multiple controllers, or just want to DRY up the process, we use this:

    #app/controllers/application_controller.rb
    private
    
    #Strong Params
    def permitted_params
        @resource =  self.resource_class
        @model = "#{@resource}".downcase.to_sym
    
        attributes = @resource.attribute_names + %w(custom items here)
        params.permit(@model => attributes)
    end