2016-07-27 41 views
0

我將我的Rails從3.2遷移到Rails 4.2.6。我有2個表,其中報告:has_many =>圖標。我爲report和icon_attributes添加了強大的參數。創建功能工作正常,並且在更新功能時,我能夠更新報告但無法更新圖標,而是每次點擊更新操作時都會創建新圖標。 這是我的代碼:無法更新Rails 4.2.6中的嵌套屬性

report.rb:

class Report < ActiveRecord::Base 
    has_many :icons, -> { order 'position_id ASC'} 
    accepts_nested_attributes_for :icons, :reject_if => lambda { |a| a[:icon].blank? }, :allow_destroy => true 
end 

icon.rb:

class Icon < ActiveRecord::Base 
    belongs_to :report 
end 

reports_controller:

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 

我已經把看跌期權看到日誌在控制器中,圖標插入爲@ report.update_attributes(report_params)步驟,這是對數:

處理由ReportsController#更新爲JSON參數: { 「UTF8」=> 「✓」, 「報告」=> {「標題「=>」title1「,」評論「=>」這是一條評論「, 」icons_attributes「=> {」0「=> {」id「=>」「,」icon「=>」market_indicator「, 「rotate」=>「0」,「top」=>「」,「_destroy」=>「false」},「id」=>「87」}

報告加載(0.3ms) 。* FROM「reports」WHERE 「reports」。「deleted_at」IS NULL AND「reports」。「id」=? LIMIT 1 [[「id」, 87]]
SQL(1.6ms)INSERT INTO「icons」(「icon」,「rotation」,「top」) VALUES(?,?,?)[[「icon 「,」market「],[」rotation「,」0「],[」top「,」「], [」left「,」「]](12.0ms)commit transaction
ActiveRecord :: Associations :: CollectionProxy

我已經把日誌爲:

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

它導致的:

圖標加載(0.9ms)選擇「圖標」。*從「圖標」其中「圖標」。「」report_id「=? ORDER BY position_id ASC [ 「REPORT_ID」,91]

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

+0

你可以發佈傳遞給你的更新操作的參數嗎? – mmichael

+0

正如我在問題中發佈的,我使用report_params作爲更新操作的參數。 – venkat

+0

我的意思是從日誌中發佈參數。它們應該看起來像'參數:{「report」=> {「title」=>「blah」,「icons_attributes」=> {etc.}}}' – mmichael

回答

0

"icon_attributes"不是沿着通過圖標的ID。

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

你會注意到id是空的。由於id是空白的,導軌認爲它是一個新的記錄,因此創建一個新的圖標。錯誤在於你如何製作表格。

+0

更新之前我正在打印圖標,id已經列出。我更新了問題,請檢查。 – venkat

+0

是的,但更新操作沒有您的日誌中顯示的ID。 – ChrisBarthol