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

How can I include an HTML input in rails strong params?

我正在尝试创建一个模型 "Post" 的实例,其中的强参数看起来像这样:

  private

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

在我的表格中,这是我将文件上传到 post_params["images"] 的方式,因此上传到 post.images:

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

但我想对上传按钮应用自定义样式,所以我使用 HTML 构建了一个。但是我无法弄清楚什么 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 输入什么名字以便它包含在强参数中?

像这样:

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

这应该会生成您的控制器所期望的正确 JSON 参数。它可能会与 hash/array 的多个级别混淆。这就是为什么我在上面的评论中提到的在浏览器中使用 inspect element 来查看 Rails 正在生成什么,然后我可以构建自定义样式元素以满足我的需要。

一种记忆方法是:您正在 require-ing post,然后寻找一个键为 images 且值类型为 [=16] 的散列=].这样就更容易知道在哪里使用单数和复数,关键是什么等等。所以在句法上将其映射为:

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

.erb 版本中,如果您查看表单的顶部,请考虑 f... do |f| 中的值。这就是它获得控制器名称 post(单数)的地方,然后您在 file_field 中为它提供方法名称 :images(复数)。根据 Rails 文档,您可以使用单数 :image 但复数对我来说似乎更正确。