【发布时间】:2018-02-08 18:10:59
【问题描述】:
我有一个用于以下模型的三重嵌套表单。
roasts、countries、regions
我可以创造一种新的烤肉,它也创造了国家,但不能创造地区。控制台输出:
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,日志有“countries_attributes”,但regions 只是“regions”,而这也应该是 region_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
将其更改为 regions_attributes: [:region_id, :region_name] 没有帮助。
roast.rb
class Roast < ApplicationRecord
has_many :tastings
has_many :countries
has_many :notes, through: :tastings
has_many :comments, as: :commentable
accepts_nested_attributes_for :countries
country.rb
class Country < ApplicationRecord
has_many :regions, inverse_of: :country
accepts_nested_attributes_for :regions
belongs_to :roasts
region.rb
class Region < ApplicationRecord
belongs_to :country, inverse_of: :regions
烘烤控制器
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>
【问题讨论】:
-
你能展示一些来自模型和控制器的代码吗?
-
Roast 模型中有
accepts_nested_attributes_for :countries吗? api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/… -
刚刚更新了模型和控制器的帖子
-
可以添加表格吗?
-
@Pablo 刚刚添加了表单字段
标签: ruby-on-rails nested strong-parameters