2016-09-06 41 views
6

我下面的教程:http://www.amooma.de/screencasts/2015-01-22-nested_forms-rails-4.2/Rails的嵌套形式的错误,孩子必须存在

我usign Rails的5.0.0.1

但是,当我注册一个酒店,它似乎是酒店类必须存在。

1错误,无法储存禁止该酒店:类别酒店必须 存在

我的酒店模式:

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

回答

17

belongs_to行为rails >= 5.x发生了变化。实质上,现在预计belongs_to记录在分配给关联的另一侧之前存在。你需要通过required :false,而在你的Category模型声明belongs_to如下:

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

感谢您的帮助,我看到'inverse_of :: categories'也适用。 –

+2

谢谢达拉姆,这有帮助。另外,请注意'required:false'已被弃用(来源:https://github.com/rails/rails/pull/18937)。更好地使用'belongs_to:hotel,可选:true' – htaidirt