How to make an optional strong parameters key yet still filter params nested in it?

£可爱£侵袭症+ 提交于 2019-12-23 06:48:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!