Search code examples
rubyruby-on-rails-4strong-parameters

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?


Solution

  • 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!