三重嵌套表单Rails 5.1上的未经许可的参数

时间:2018-02-08 18:11:00

标签: ruby-on-rails nested strong-parameters

我有以下型号的三重嵌套表格。

roastscountriesregions

我可以创造一个新的烤肉,它也创造了国家,但不是该地区。控制台输出:

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"cR5jRFbaslQU5+nWiU8rBWlC9OQ0E9zgMwY1YCF33Z1cwPkmJvsO5GKQ4hTNIB4Mku3EuL19WJTrg4e03gHW4Q==", "roast"=>{"roaster"=>"Square Mile", "name"=>"Red Brick", "countries_attributes"=>{"0"=>{"country_name"=>"UK"}}, "regions"=>{"region_name"=>"Midlands"}, "bestfor"=>"", "roast"=>"", "tastingnotes"=>""}, "commit"=>"Create Roast"}
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."user_id" = $1 ORDER BY "users"."user_id" ASC LIMIT $2  [["user_id", 15], ["LIMIT", 1]]
Unpermitted parameter: :regions

我注意到的是,countries对于regions,日志有“countries_attributes”,但def roast_params params.require(:roast).permit(:roaster, :name, :bestfor, :beans, :roast, :tastingnotes, :notes, :slug, :avatar, countries_attributes: [:country_id, :country_name, regions_attributes: [:id, :region_name]]) end 只是“region”,这也应该是regions_attributes。我把国家控制器中的区域参数嵌套在国家参数中。那是对的吗?我试过它们没有嵌套,这也不起作用:

我的参数:

regions_attributes: [:region_id, :region_name]

将此更改为class Roast < ApplicationRecord has_many :tastings has_many :countries has_many :notes, through: :tastings has_many :comments, as: :commentable accepts_nested_attributes_for :countries 无效。

roast.rb

class Country < ApplicationRecord
  has_many :regions, inverse_of: :country
  accepts_nested_attributes_for :regions
  belongs_to :roasts

country.rb

class Region < ApplicationRecord
  belongs_to :country, inverse_of: :regions

region.rb

  def new
    @roast = Roast.new
    @roast.countries.build.regions.build
  end

烤制控制器

  <div class="form-group">
    <%= form.fields_for :countries do |countries_form| %>
      <%= countries_form.label :country %>
      <%= countries_form.text_field :country_name, class: "form-control" %>
<br />
      <%= form.fields_for :regions do |regions_form| %>
        <%= regions_form.label :region %>
        <%= regions_form.text_field :region_name, class: "form-control" %>
      <% end %>
    <% end %>
  </div>

嵌套字段的表单

require "fileutils"

FileUtils.chmod("+x", "foo.sh")

1 个答案:

答案 0 :(得分:0)

我认为

<%= form.fields_for :regions do |regions_form| %>
    <%= regions_form.label :region %>
    <%= regions_form.text_field :region_name, class: "form-control" %>
<% end %>

应该是

<%= countries_form.fields_for :regions do |regions_form| %>
    <%= regions_form.label :region %>
    <%= regions_form.text_field :region_name, class: "form-control" %>
<% end %>