Rails - Strong parameters with empty arrays

后端 未结 5 1731
星月不相逢
星月不相逢 2021-02-01 13:37

I\'m sending an array of association ids, say foo_ids to my controller. To permit an array of values, I use:

params.permit(foo_ids: [])
5条回答
  •  醉话见心
    2021-02-01 14:36

    The temporary solution I've come down to is:

    params[:foo_ids] ||= [] if params.has_key?(:foo_ids)
    params.permit(foo_ids: [])
    

    Here, foo_ids is set to an empty array only if is passed. If it is not passed in the request, it is ignored.

    I'm still hoping to find a better solution to this, as this sort of thing will be quite common in the project I'm working on - please do suggest better ideas if you have any.

提交回复
热议问题