Rails nested form error, child must exist

柔情痞子 提交于 2019-12-01 15:45:52

问题


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

回答1:


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 required :false while declaring belongs_to in your Category model as follows:

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


来源:https://stackoverflow.com/questions/39359168/rails-nested-form-error-child-must-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!