Rails 5 错误消息:子模型父模型必须存在

2024-05-07

我有两个模型,父模型是财产,子模型是电话。当尝试使用嵌套电话数据创建新的属性记录时,我收到一条错误消息:Phones 属性必须存在。

我研究了 Rails Guide 和许多其他文档,但没有确定原因。如果你想查看所有代码,这里有一个公共 github 链接:https://github.com/allenroulston/testnest.git https://github.com/allenroulston/testnest.git

class Property < ApplicationRecord
  has_many :phones
  accepts_nested_attributes_for :phones
end

class Phone < ApplicationRecord
  belongs_to :property
end

# the form accepting the data
<%= form_for(property) do |f| %>
  <% if property.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(property.errors.count, "error") %> prohibited this property from being saved:</h2>

      <ul>
      <% property.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <%= f.label :address %>
    <%= f.text_field :address %>
  </div>

  <div class="field">
    <%= f.label :city %>
    <%= f.text_field :city %>
  </div>

  <div class="field">
    <%= f.label "Telephone (example: 613 555 1234 )" %>
    <%= f.fields_for :phones do |p| %>
      Area Code <%= p.text_field :area %>
      Exchange <%= p.text_field :exchange %>
      Number <%= p.text_field :number %>
    <% end %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>


 # relevant controller methods ##################

 # GET /properties/new
  def new
    @property = Property.new
    @property.phones.build
  end

  # POST /properties
  # POST /properties.json
  def create
    @property = Property.new(property_params)

    respond_to do |format|
      if @property.save
        format.html { redirect_to @property, notice: 'Property was successfully created.' }
        format.json { render :show, status: :created, location: @property }
      else
        format.html { render :new }
        format.json { render json: @property.errors, status: :unprocessable_entity }
      end
    end
  end

据我所知,这是因为当您在创建新对象时使用nested_attributes_for时,父对象尚未创建,因此当尝试创建对父对象的引用时,验证失败。要解决此问题,您应该更改为:has_many :phones, inverse_of: :property.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 5 错误消息:子模型父模型必须存在 的相关文章

随机推荐