Rails nested form error, child element must exist

I follow the tutorial: http://www.amooma.de/screencasts/2015-01-22-nested_forms-rails-4.2/

I am using Rails 5.0.0.1

But when I check in a hotel, it seems that a hotel category should exist.

1 error has forbidden this hotel to be saved: Hotel categories must exist

My hotel model:

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 

Model of my category:

 class Category < ApplicationRecord belongs_to :hotel validates :name, presence: true end 

My hotel controller:

 def new @hotel = Hotel.new @hotel.categories.build end def hotel_params params.require(:hotel).permit(:name, categories_attributes: [ :id,:name]) end 

Complete my _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 %> 
+6
source share
1 answer
Behavior

belongs_to has changed in rails >= 5.x belongs_to Essentially, it now expects the belongs_to entry belongs_to exist before assigning it to the other side of the association. You need to pass required :false , declaring belongs_to in your Category model as follows:

 class Category < ApplicationRecord belongs_to :hotel, required: false validates :name, presence: true end 
+17
source

All Articles