Question

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.

Was it helpful?

Solution 3

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

OTHER TIPS

One shortcut you can do if you have say around 20 columns in your model and you don't need to specify all columns inside permit in your controller then it as:

params.require(:person).permit!

This will permit all the attributes from your model

Here's a quick "getting started" tip regarding cases where you have "lots" of fields for your model Foo... rather then whitelist them all, auto-generate a list then remove the ones you know should not be mass-assigned.

In rails console you can get a symbol list of all fields very easily, copy/paste it to the permit(...) method, then remove the ones that should not be mass-assigned like :id, :ctreated_at, :admin, etc

Foo.attribute_names.map(&:to_sym).sort
> [:address, :admin, :created_at, :id, :name, :updated_at]

This takes only a few seconds longer than using the .permit! approach, but gives you a better starting point from a security point of view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top