How to make an optional strong parameters key but filter nested params?

snitko picture snitko · Jul 16, 2013 · Viewed 10.9k times · Source

I have this in my controller:

params.require(:item).permit!

Let's assume this rspec spec, which works as expected:

put :update, id: @item.id, item: { name: "new name" }

However, the following causes ActionController::ParameterMissing:

put :update, id: @item.id, item: nil

It has to do with controller macros that I use for other actions and through which I cannot control the params being sent (the macros checks for user credentials, so I don't really care about actually testing an #update action, rather I just test before_filters for it).

So my question is: How do I make params[:item] optional, yet still filter attributes within it if it's present?

Answer

Damien Roche picture Damien Roche · Jul 17, 2013

What about:

params.require(:item).permit! if params[:item]

You cannot require an optional parameter. That is contradictory.

Edit: as mtjhax mentioned in his comment, there is advice from here to use fetch instead: params.fetch(:item, {}).permit!