问题
I have this in my controller:
params.require(:item).permit!
Let's assume this rspec spec:
put :update, id: @item.id, item: { name: "new name" }
It works as expected, no error. However, if I use this:
put :update, id: @item.id, item: nil
I get ActionController::ParameterMissing
which I don't want to get. 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?
回答1:
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!
来源:https://stackoverflow.com/questions/17687506/how-to-make-an-optional-strong-parameters-key-yet-still-filter-params-nested-in