代码之家  ›  专栏  ›  技术社区  ›  Joe Morano

如何在rails强参数中包含HTML输入?

  •  0
  • Joe Morano  · 技术社区  · 8 年前

    我正在尝试创建一个带有如下强参数的模型“Post”实例:

      private
    
        def post_params
          params.require(:post).permit(:name, {images: []})
        end
    

    post_params["images"] ,因此 post.images :

    <%= f.file_field :images, multiple: true %>
    

    name 属性来提供输入,以便将其包含在 post_params . 我试过的是:

    <input name="images" type="file" multiple="true"/>
    <input name="post[images]" type="file" multiple="true"/>
    <input name="post['images']" type="file" multiple="true"/>
    <input name=":images" type="file" multiple="true"/>
    

    但他们都去了 params["post"]["images"] ,不是 strong_params .

    我可以给HTML输入什么名字,以便它包含在强参数中?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Beartech    8 年前

    像这样的:

    <input multiple="multiple" name="post[images][]" id="posts_images" type="file">
    

    inspect element 在上面我的评论中提到的浏览器中查看Rails正在生成什么,然后我可以构建定制样式的元素来满足我的需要。

    require -ing post ,然后查找键为 images 以及类型的值 array

    <model name>[<key defined in strong params>][]
    

    .erb 版本如果你看一下表单的顶部,想想 f 是在 ... do |f| . 这就是它获取控制器名称的地方 邮递 :images (复数)在 file_field . 根据Rails文档,您可以使用单数 :image