Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails nested form error, child must exist

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

I'm usign Rails 5.0.0.1

But when I register a hotel, it appears that the hotel category must exist.

1 error prohibited this hotel from being saved: Categories hotel 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

My Category model:

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

End 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 %>
like image 672
Gleydson S. Tavares Avatar asked Sep 06 '16 23:09

Gleydson S. Tavares


1 Answers

belongs_to behavior has changed in rails >= 5.x. Essentially it is now expected that the belongs_to record exists before assigning it to the other side of the association. You need to pass optional: true while declaring belongs_to in your Category model as follows:

class Category < ApplicationRecord
  belongs_to :hotel, optional: true
  validates :name, presence: true
end 
like image 54
Dharam Gollapudi Avatar answered Oct 21 '22 08:10

Dharam Gollapudi