【发布时间】:2018-02-02 21:14:53
【问题描述】:
我有两个模型,Countries 和 Regions。我正在尝试将区域设置为国家的嵌套属性。到目前为止,我的代码将国家写入数据库,但没有写入区域。我没有错误。
就关系而言,我不确定的另一件事是,用户应该添加一个嵌套了国家/地区的区域,还是反过来让用户添加一个嵌套了区域的国家/地区?
country.rb
class Country < ApplicationRecord
has_many :regions, inverse_of: :country
has_many :roasts
accepts_nested_attributes_for :regions
validates :name, presence: true
end
region.rb
class Region < ApplicationRecord
belongs_to :country, inverse_of: :region
validates :name, uniqueness: true
validates :name, presence: true
end
country_controller.rb
def country_params
params.require(:country).permit(:name, :description, regions_attributes: [:id, :name, :description])
end
国家/地区/_form.html.rb
<%= form_with(model: country, local: true) do |form| %>
<% if country.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(country.errors.count, "error") %> prohibited this country from being saved:</h2>
<ul>
<% country.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name, id: :country_name %>
</div>
<div class="field">
<%= form.label :description %>
<%= form.text_field :description, id: :country_description %>
</div>
//nested region form
<%= form.fields_for :region do |region| %>
<p>
Region: <%= region.text_field :name %>
</p>
<% end %>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
更新
Region 不是允许的参数。检查控制器,我有它作为参数?
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wUtZvA8rMeQ12onWg+B4OcbzGzZOIDOLwi99Aef3SnjAg5yyYA0qI8wNJIl41u/S0+RIlMAvkVwWVyWWPF3Ocg==", "country"=>{"name"=>"Guatemala", "description"=>"", "region"=>{"name"=>"Candelaria"}}, "commit"=>"Create Country"}
Unpermitted parameter: :region
(0.1ms) BEGIN
SQL (0.8ms) INSERT INTO "countries" ("name", "description", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["name", "Guatemala"], ["description", ""], ["created_at", "2018-02-02 22:21:24.093876"], ["updated_at", "2018-02-02 22:21:24.093876"]]
(0.3ms) COMMIT
Redirected to http://localhost:3000/countries/10
Completed 302 Found in 5ms (ActiveRecord: 1.2ms)
更新 2
我现在允许区域参数,但似乎我实际上并没有发送任何指令来创建区域。因此,我补充说:
def new
@country = Country.new
@country.region.build //doesn't work
@country.regions.build //doesn't work
@country.build_region //doesn't work
@country.build_regions //doesn't work
end
但这只会产生错误undefined method 'build' for nil:NilClass
【问题讨论】:
标签: ruby-on-rails nested-forms