ruby-on-rails – Rails嵌套表单错误,子必须存在
发布时间:2020-12-16 21:19:40 所属栏目:百科 来源:网络整理
导读:我正在按照教程: http://www.amooma.de/screencasts/2015-01-22-nested_forms-rails-4.2/ 我正在使用Rails 5.0.0.1 但是当我注册酒店时,似乎酒店类别必须存在. 1 error prohibited this hotel from being saved: Categories hotel must exist 我的酒店型号
我正在按照教程:
http://www.amooma.de/screencasts/2015-01-22-nested_forms-rails-4.2/
我正在使用Rails 5.0.0.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 <%= 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 %> 解决方法
在rails> = 5.x中,belongs_to行为已更改.基本上,现在预期belongs_to记录在将其分配给关联的另一侧之前存在.您需要在Category模型中声明belongs_to时传递required:false,如下所示:
class Category < ApplicationRecord belongs_to :hotel,required: false validates :name,presence: true end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |