嵌套字段模型不保存Rails中的父关联

时间:2016-01-13 05:25:17

标签: ruby-on-rails

我的rails应用中有一个SaleQualifier模型has_many answers。在尝试同时保存sale_qualifieranswer我收到错误Answers sale_qualifier can't be blank时,我无法解决问题所在,因为我'我们在应用程序上以其他形式使用这些嵌套属性。

SaleQualifier页面上显示SalesOpportunity,因此我首先在SalesOpportunity show操作中对此进行定义:

  def show
   @sales_opportunity = SalesOpportunity.includes(:company, :user, :timeline_events, :sale_contacts, :swots, :sale_competitors).find(params[:id])
   @sale_qualifier = SaleQualifier.new(sales_opportunity_id: params[@sales_opportunity.id])
   @answer = @sale_qualifier.answers.build
 end

正如您所看到的,我在show controller中构建关联,然后应该通过SaleQualifier create操作进行更新。在SaleQualifier控制器中,我设置了以下内容:

    def sale_qualifier_params
     params.require(:sale_qualifier).permit(:question_id, :answer_id, :next_question_id, :answered, :sales_opportunity_id, answers_attributes: [:answer_text, :sale_qualifier_id])
   end

我的销售限定符代码:

class SaleQualifier < ActiveRecord::Base
 has_many :answers, :inverse_of => :sale_qualifier
 accepts_nested_attributes_for :answers
 belongs_to :sales_opportunity
 validates :sales_opportunity_id, presence: true
end

我的答案.rb:

class Answer < ActiveRecord::Base
 validates :answer_text, presence: true
 belongs_to :sale_qualifier
 validates :sale_qualifier_id, presence: true
end

我的观点:

<div class="panel panel-default">
 <%= form_for(@sale_qualifier) do |f| %>
 <% if @sale_qualifier.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@sale_qualifier.errors.count, "error") %> prohibited this answer from being saved:</h2>
    <ul>
    <% @sale_qualifier.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
    </ul>
  </div>
<% end %>
<div class="panel-body">
  <div class="col-sm-6">
    <h2><%= @question.question_text %></h2>
  </div>
  <div class="col-sm-6">
    <div class="form-group">
      <%= f.hidden_field :sales_opportunity_id, :value => @sales_opportunity.id %>
    </div>
    <%= f.fields_for :answers do |answer| %>
        <%= answer.text_area :answer_text, :placeholder => "Enter your answer" %>
    <% end %>
    <div class="actions">
      <%= f.submit "Submit", class: "btn btn-large btn-success"%>
    </div>
    <% end %>
  </div>
 </div>
</div>

所有字段都在视图上正确显示。这是提交按钮单击的日志文件:

Started POST "/sale_qualifiers" for 127.0.0.1 at 2016-01-13 13:12:57 +0800
Processing by SaleQualifiersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"0NdiFqK9O2fqh7TvDamrUL4jeQ6otcoQGhBZX9DlaSg=", "sale_qualifier"=>{"sales_opportunity_id"=>"77", "answers_attributes"=>{"0"=>{"answer_text"=>"An Answer"}}}, "commit"=>"Submit"}

错误返回&#34;答案sale_qualifier不能为空白&#34;。

我确定在我的代码中无法看到一些直接的错误,如果有人能帮我找到它,我会很感激。

1 个答案:

答案 0 :(得分:1)

像往常一样,在这里发布问题之后不久就回答了我。这是我代码中的违规行:

validates :sale_qualifier_id, presence: true

删除它可以让我更新sale_qualfiier和答案。