Rails - Strong parameters with empty arrays

后端 未结 5 1729
星月不相逢
星月不相逢 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:38

    This is quite late, but I just had this problem myself. I solved it by including both the scalar version and array version in the permit statement, like so:

    params.require(:photo).permit(:tags, tags: [])
    

    FYI - it has to have both in the same permit statement - if you chain them it'll get thrown out for some reason.

    EDIT: I just noticed that an empty array submitted via this method will be turned into nil - I've now got a bunch of fields that should be empty arrays that are nil. So the solution I posted doesn't actually work for me.

    EDIT the second: Thought I had already added this, but this problem is related to Rails performing deep_munge on params hashes. This comment explains how to fix it: https://stackoverflow.com/a/25428800/130592

提交回复
热议问题