Rails - Strong parameters with empty arrays

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

    I had the same problem recently, but none of the answers here worked for me. This is my solution. If you have javascript handling HTTP requests, this may work for you, too.

    In your client side:

    if (photo.tags.length === 0){
      photo.tags = ["null"]
    }
    

    And on your PhotosController

    def photo_params
      p = params.require(:photo).permit(tags: [])
      p["tags"].reject! { |tag| tag == "null" }
      p
    end
    

提交回复
热议问题