Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – Rails嵌套表单错误,子必须存在大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在按照教程: 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

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – Rails嵌套表单错误,子必须存在全部内容,希望文章能够帮你解决ruby-on-rails – Rails嵌套表单错误,子必须存在所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: