Rails 嵌套表单错误,子项必须存在
Rails nested form error, child must exist
我正在学习教程:http://www.amooma.de/screencasts/2015-01-22-nested_forms-rails-4.2/
我用的是Rails5.0.0.1
但是我注册酒店的时候,好像酒店类别必须存在。
1 error prohibited this hotel from being saved: Categories hotel must
exist
我的酒店模型:
class Hotel < ApplicationRecord
has_many :categories, dependent: :destroy
validates :name, presence: true
accepts_nested_attributes_for :categories, reject_if: proc { |attributes| attributes['name'].blank? }, allow_destroy: true
end
我的分类模型:
class Category < ApplicationRecord
belongs_to :hotel
validates :name, presence: true
end
我的酒店管理员:
def new
@hotel = Hotel.new
@hotel.categories.build
end
def hotel_params
params.require(:hotel).permit(:name, categories_attributes: [ :id,:name])
end
结束我的_form.html.erb
<%= f.fields_for :categories do |category| %>
<div class="room_category_fields">
<div class="field">
<%= category.label :name %><br>
<%= category.text_field :name %>
</div>
</div>
<% end %>
belongs_to
行为在 rails >= 5.x
中发生了变化。本质上,现在期望 belongs_to
记录在将其分配给关联的另一端之前存在。您需要在 Category
模型中声明 belongs_to
时传递 optional: true
,如下所示:
class Category < ApplicationRecord
belongs_to :hotel, optional: true
validates :name, presence: true
end
我正在学习教程:http://www.amooma.de/screencasts/2015-01-22-nested_forms-rails-4.2/
我用的是Rails5.0.0.1
但是我注册酒店的时候,好像酒店类别必须存在。
1 error prohibited this hotel from being saved: Categories hotel must exist
我的酒店模型:
class Hotel < ApplicationRecord
has_many :categories, dependent: :destroy
validates :name, presence: true
accepts_nested_attributes_for :categories, reject_if: proc { |attributes| attributes['name'].blank? }, allow_destroy: true
end
我的分类模型:
class Category < ApplicationRecord
belongs_to :hotel
validates :name, presence: true
end
我的酒店管理员:
def new
@hotel = Hotel.new
@hotel.categories.build
end
def hotel_params
params.require(:hotel).permit(:name, categories_attributes: [ :id,:name])
end
结束我的_form.html.erb
<%= f.fields_for :categories do |category| %>
<div class="room_category_fields">
<div class="field">
<%= category.label :name %><br>
<%= category.text_field :name %>
</div>
</div>
<% end %>
belongs_to
行为在 rails >= 5.x
中发生了变化。本质上,现在期望 belongs_to
记录在将其分配给关联的另一端之前存在。您需要在 Category
模型中声明 belongs_to
时传递 optional: true
,如下所示:
class Category < ApplicationRecord
belongs_to :hotel, optional: true
validates :name, presence: true
end