2013-01-01 37 views
0

我正在用rails 3.2.8編寫一個小CMS應用程序。有段落模型(基本上包含例如新聞文章的標題,正文和日期)和頁面(包括許多段落,例如許多新聞文章)。如果日期發生變化,以下內容只會更新一個段落,否則,段落不會更新,即使例如。身體改變了!?update_attributes在某些情況下不會更新nested_attributes

page.update_attributes({"paragraphs_attributes"=>{"0"=>{"_destroy"=>"0", 
      "title"=>"News title", "body"=>"News text", "id"=>"4", 
      "date(3i)"=>"1", "date(2i)"=>"1", "date(1i)"=>"2013"}}}) 

下面,你可以找到模型的相關部分:

page.rb

class Page < ActiveRecord::Base 
    has_many :paragraphs, :dependent => :destroy 
    attr_accessible :name, :paragraphs_attributes 
    accepts_nested_attributes_for :paragraphs, :allow_destroy => true 
end 

paragraph.rb

class Paragraph < ActiveRecord::Base 
    belongs_to :page 
    attr_accessible :title, :body, :page, :date 
    validates :page, presence: true 
end 

是否有人有關於任何想法這種奇怪的行爲的原因?

回答

0

當然可能存在骯髒的解決方法:在最終更新之前插入僞造更新。請注意,這是非常糟糕的風格和雙打用於更新的數據庫訪問,但因爲我無法找到另一種解決方案,我想出了以下解決方案:

page_controller.rb

class PageController < ApplicationController 

    def update 

    # Hack: Updating paragraphs fails for some strange reasons if their date 
    # did not change. Updating paragraphs with date changes works as expected. 
    # To allow updates in all cases, we first make an update to an impossible 
    # date and then make an update to the real date. 


    # Define a year, that will never occure in the params. 
    # This date will be used for the fake update. 
    impossible_year = "1999" 

    # Setup the fake params for the first fake update (Change the date fields of 
    # all paragraphs to an impossible date). 
    fake_params = params[:page].deep_dup 
    par_attrs = fake_params[:paragraphs_attributes] 
    par_attrs.keys.each do |key| 
     par_attrs[key]["date(1i)"] = impossible_year 
    end 

    # Perform the fake update. 
    @page.update_attributes(fake_params) 

    # Finally do the real update with the original params. 
    @page.update_attributes(params[:page]) 
    end 
end 
相關問題