Rails 5错误消息:Child-Model Parent-Model必须存在

All*_*ton 4 nested-attributes ruby-on-rails-5

我有两个型号,父母是财产,孩子是电话.尝试使用嵌套的Phone数据创建新的Property记录时,收到错误消息:Phones属性必须存在.

我已经研究过Rails指南和许多其他文档而没有确定原因.如果你想看到所有代码,这是一个公共github链接: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
Run Code Online (Sandbox Code Playgroud)

Kku*_*kis 18

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

  • @AllenRoulston很好的解读 - https://www.viget.com/articles/exploring-the-inverse-of-option-on-rails-model-associations欢迎你们:)如果你查了一下会很感激问题回答:) (3认同)
  • `has_many :phones, inverse_of: :property` 确实解决了“验证”错误,尽管我承认我需要做一些阅读以了解它为什么/如何解决问题。谢谢你。 (2认同)