无法在Rails 4.2.6中更新嵌套属性

时间:2016-07-27 18:16:59

标签: ruby-on-rails activerecord strong-parameters

我将我的Rails从3.2迁移到Rails 4.2.6。我有2个表格,其中报告:has_many =>图标即可。我为report和icon_attributes添加了强大的参数。创建功能工作正常,在更新功能时,我能够更新报告但无法更新图标,而是每次点击更新操作时都会创建新图标。 这是我的代码:

report.rb:

class Icon < ActiveRecord::Base
  belongs_to :report
end

icon.rb:

  def update
    respond_to do |format|
      if @report.update_attributes(report_params)
        @report.save
        format.html { redirect_to(user_reports_url, :notice => 'Report was successfully updated.') }
        format.json { render :json => { :success => true, :report_id => @report.id, :report_title => @report.title, :icon_array => @report.icons, :redirect => report_url(@report.id) } }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @report.errors, :status => :unprocessable_entity }
      end
    end
  end

  private

  def report_params
    params.require(:report).permit(:title, :comments, :remarks,{:icons_attributes => [:id, :icon, :rotation, :top, :_destroy]})
  end

reports_controller:

  def update
    puts @report.icons.inspect
    respond_to do |format|
     .....
  end

我通过将 puts 放在控制器中看到了日志,图标插入 @ report.update_attributes(report_params)步骤,这是日志:

  

ReportsController处理#update为JSON参数:   {&#34; utf8&#34; =&gt;&#34;✓&#34;,&#34;报告&#34; =&gt; {&#34;标题&#34; =&gt;&#34; title1& #34;,&#34;评论&#34; =&gt;&#34;这是评论&#34;,   &#34; icons_attributes&#34; =&gt; {&#34; 0&#34; =&gt; {&#34; id&#34; =&gt;&#34;&#34;,&#34; icon&# 34; =&GT;&#34; market_indicator&#34 ;,   &#34;轮换&#34; =&gt;&#34; 0&#34;,&#34;顶部&#34; =&gt;&#34;&#34;,&#34; _destroy&#34; =&gt; ;&#34; false&#34;},&#34; id&#34; =&gt;&#34; 87&#34;}

     

报告加载(0.3ms)SELECT&#34;报告&#34;。* FROM&#34;报告&#34;哪里   #&34;报告&#34;&#34; deleted_at&#34; IS NULL和&#34;报告&#34;。&#34; id&#34; =?限制1 [[&#34; id&#34;,   87]]
  SQL(1.6ms)INSERT INTO&#34; icons&#34; (&#34;图标&#34;,&#34;轮换&#34;,&#34;顶部&#34;)   价值观(?,?,?)[[&#34;图标&#34;,&#34;市场&#34;],[&#34;轮换&#34;,&#34; 0&#34;],[ &#34; top&#34;,&#34;&#34;],   [&#34; left&#34;,&#34;&#34;]](12.0ms)提交交易
   ActiveRecord :: Associations :: CollectionProxy

我已将日志设为:

<ActiveRecord::Associations::CollectionProxy [#<Icon id: 204, report_id: 91, icon: "asking_price", rotation: "", top: "150", left: "165">]>

结果为:

图标加载(0.9ms)SELECT&#34;图标&#34;。* FROM&#34;图标&#34;在哪里&#34;图标&#34;。&#34; report_id&#34; =? ORDER BY position_id ASC [[&#34; report_id&#34;,91]]

{{1}}

1 个答案:

答案 0 :(得分:0)

您的"icon_attributes"未传递图标的ID。

"icons_attributes"=>{"0"=>{"id"=>"", "icon"=>"market_indicator", "rotation"=>"0", "top"=>"", "_destroy"=>"false"}, "id"=>"87"}

您会注意到ID是空白的。由于id为空白,因此rails认为它是一个新记录,因此创建了一个新图标。错误在于你如何制作表格。