2010-09-27 22 views
2

我有以下情況用ActiveRecord在相關兒童的變化(在Rails的2.3.8):現在ActiveRecord改變了嗎?標誌不報告

class Order < ActiveRecord::Base 
    has_many :documents 
    accepts_nested_attributes_for :documents 
end 

class Document <ActiveRecord::Base 
    belongs_to :order 
end 

,在控制器我想直接的用戶不同,這取決於是否或者他們沒有改變現有記錄,例如

@order.attributes = params[:order] 
if @order.changed? 
    # save order 
    # redirect one place 
else 
    # redirect another place 
end 

爲此,我想使用更改?旗。事實證明,@ order.changed?不詢問孩子。

我試圖實現一個通過在的has_many關聯代理方法:文件的關聯,就像這樣:

has_many :documents do 
    def changed? 
     any? {|doc| doc.changed?} 
    end 
    end 

但是,這是它從磁盤加載的相關文件時,意想不到的副作用,這顯然抹掉了@ order.attributes = params [:order]中的嵌套屬性賦值中所做的任何更改。這似乎是Rails中的有意設計決策,但是接下來如何解決它?或者它是一個功能差距?

想法?

+0

需要 'DM-核心' 需要 'DM-遷移' 需要 'DM-accepts_nested_attributes' Order類 包括DataMapper的資源::物業 :ID,序列 有n個,:文件 accepts_nested_attributes_for:文件 結束 類文獻 包括的DataMapper ::資源 屬性:ID,序列 屬性:FOO,字符串 belongs_to的:爲了 端 數據Mapper.setup(:默認,'sqlite :: memory:') DataMapper.auto_migrate! @o = Order.create @ o.attributes = {'documents'=> [{'foo'=>'bar'}]} @ o.documents.any? {| DOC | doc.dirty?} – Reactormonk 2010-09-27 21:16:26

回答

4

你可能有一個看的nested_records_changed_for_autosave源。

這不完全是你想要的,但它有關於如何做到這一點的線索。特別是association_instance_get其中「如果它響應:裝載?獲取指定的關聯實例,否則爲零」。

+0

謝謝你的建議。這導致我們走下調查的正確道路。 事實證明,我們的實際問題與任何由嵌套屬性創建的內存對象在各種驗證規則中被覆蓋以及before_save掛鉤無意中從磁盤加載關聯有關,特別是:validates_presence_of:Order模型中的文檔將使用嵌套屬性進行更新。 – 2010-09-28 21:09:32

+0

沒問題,很高興有幫助。 – hellvinz 2010-09-29 15:30:53

+0

謝謝!我想要檢測某個對象是否將其關聯從持久對象更改爲非持久對象。 'changes'方法會將新值作爲空白字符串返回,因爲它需要一個ID。 'object.association(attribute.gsub'_id','').target'爲我做了詭計! – zykadelic 2016-07-13 19:45:12