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 %>
source share