Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 620
snitko Avatar asked Jul 16 '13 21:07

snitko


1 Answers

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!

like image 83
Damien Roche Avatar answered Nov 07 '22 14:11

Damien Roche