Post Format

Migrate a Ruby on Rails App to Rails 4.x with “Strong Parameters”

Ruby Logo

A helpful rake task

I’m just updating a three year old rails app from 3.2 to 4.2. One of the changes is that now the controller is responsible to protect against mass assignments.
I think this is the right architecture, as the controller has the job to receive the input parameters and transfer them to the right model, or reject the request altogether. The browser of the user does not talk directly with the model, and the model does not know which user with which rights has done a request.

With the strong parameters, all allowed parameters need to be in a white list. My app has 60 controllers, so writing all the code for the strong parameters is a big task. For each controller you need to collect the right attributes and put them in the permit-call.

I have done some internet research if there are solutions to simplify it, but I found no good solution.

So I have created a rake task. The task generates the source code of parameter-checking-methods, with all the fields for each model.

The output look like this:

def modelname_params
  params.require(:modelname).
    permit(:attribut1, :attribut2, ....)
end

You can pipe the output into a file and than copy & paste the whole method into your controller.
You still need to remove unwanted fields, but you no longer need to write the method from scratch and copy & paste each of the fields individually.

Here you find the gist of my strong-methods rake task.

Author: Karsten Meier

Weil ich gerne Probleme löse bin ich Informatiker geworden. Für meine Kunden berate und konzeptioniere ich und entwickle mit fast allem, was einen Prozessor hat. Sie finden mich auch auf Twitter

Leave a Reply

Required fields are marked *.