首页 > 解决方案 > 带有动态参数的 rails 4 中不允许的参数

问题描述

我在 Rails 应用程序中使用 Simple Form,其中 FormsController 控制器定义如下:

class FormsController < ApplicationController
  def index
      @forms = Form.all
  end

  def new
    @form = Form.new(form_params)
    @index = 1 # use 1 to test
  end

  ...

  private
    def form_params
      params.require(:form).permit(:user, :name, :tag, :link, :repo)
    end
end

链接的应用程序视图:

<div class="form">
  <%= simple_form_for @param do |f| %>
    <div class="form-inputs";>
      <%= f.input :user %>
      <%= f.input :name %>
      <%= f.input :tag %>
      <%= f.input :link %>
      <%= f.input :repo %>
    </div>
    <div class="form-actions">
      <%= f.button :submit, "Create", class: "btn-primary" %>
    </div>
  <% end %>
</div>

我使用以下参数发出了一个 http 请求:

Parameters: {"utf8"=>"✓&quot;, "authenticity_token"=>"MAUm1zINofwLSiwGLsDD7RcZIpR52Z9RQZsNjiwrIASsshNIDUOycs2MkJH+tHvekWrmhk+4pMzmHvklZNmCMw==", "form"=>{"user"=>"val1", "name"=>"val1", "tag"=>"val1", "link"=>"val1", "repo"=>"val1"}, "commit"=>"Create"}

 (0.3ms)  BEGIN
SQL (0.9ms)  INSERT INTO "forms" ("user", "name", "tag", "link", "repo", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["user", "val1"], ["name", "val1"], ["tag", "val1"], ["link", "val1"], ["repo", "val1"], ["created_at", "2020-06-21 19:34:58.119471"], ["updated_at", "2020-06-21 19:34:58.119471"]]
 (5.8ms)  COMMIT

我使用 input_html 选项修改了 html 名称属性,如下所示:

   <div class="form-inputs";>
      <%= f.input :user, input_html: { name: "form[#{@index}][user]" } %>
      <%= f.input :name, input_html: { name: "form[#{@index}][name]" } %>
      <%= f.input :tag, input_html: { name: 'form[#{@index}][tag]' } %>
      <%= f.input :link, input_html: { name: 'form[#{@index}][link]' } %>
      <%= f.input :repo, input_html: { name: 'form[#{@index}][repo]' } %>
    </div>

从现在开始,控制器在提交新表单时获取这些参数:

Parameters: {"utf8"=>"✓&quot;, "authenticity_token"=>"bUGptr2P1hhn5DFsulxQW+Iy/W5aX/xASaxUKPTvdVrx9pwpgsHFlqEijftqKOhoZEE5fGw+x93uKaCDvB3XbQ==", "form"=>{"1"=>{"user"=>"val1", "name"=>"val1", "tag"=>"val1", "link"=>"val1", "repo"=>"val1"}}, "commit"=>"Create"}

Unpermitted parameter: 1
 (0.1ms)  BEGIN
SQL (0.2ms)  INSERT INTO "forms" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"  [["created_at", "2020-06-21 19:35:44.783270"], ["updated_at", "2020-06-21 19:35:44.783270"]]
 (0.5ms)  COMMIT

由于不允许的参数,数据不再保存在数据库中。是否有必要添加一个特定的条目来完成这项工作?

标签: ruby-on-railsruby-on-rails-4

解决方案


推荐阅读