2011-05-30 44 views
4

我正在將數據與iPhone應用程序同步,因此瞭解哪些記錄「已實際」更新以及哪些記錄未更新很重要。我有一個RelatedLink關聯的事件模型:Rails ActiveRecord:accept_nested_attributes_for是否將父記錄標記爲髒,即使父屬性未更改?

在event.rb:

has_many :related_links 
accepts_nested_attributes_for :related_links, :reject_if => lambda { |a| a[:url].blank? && a[:id].blank? }, :allow_destroy => true 

在我的活動形式,當我改變什麼,包括RelatedLink場,我很好...我的事件模型沒有更新。但是如果我在我的相關鏈接字段中輸入一個url,我的Event對象上的「updated_at」就會更新。

UPDATE "events" SET "updated_at" = '2011-05-30 15:27:03.228435' WHERE "events"."id" = 1791 

它應該這樣工作嗎?我可以阻止它被標記爲髒並正在更新嗎?

回答

3

如果父模型的屬性不會再更改記錄不被認爲是骯髒和updated_at不應該改變。藉此例如(Rails的3.2.3)

Post模型

class Post < ActiveRecord::Base 
    attr_accessible :title, :body, :comments_attributes 

    has_many :comments 
    accepts_nested_attributes_for :comments 
end 

評價模型

class Comment < ActiveRecord::Base 
    attr_accessible :body, :author 
    belongs_to :post 
end 

Rails的控制檯測試(我只保留相關的輸出,當我將這些中)

1.9.3p194 :001 > p = Post.create :title => "Nested attributes", :body => "Nested attributes are awesome", :comments_attributes => [{ :body => "I agree", :author => "Bart" }] 
=> #<Post id: 1, title: "Nested attributes", body: "Nested attributes are awesome", created_at: "2012-06-13 01:49:34", updated_at: "2012-06-13 01:49:34"> 

1.9.3p194 :002 > last_post = Post.last 
=> #<Post id: 1, title: "Nested attributes", body: "Nested attributes are awesome", created_at: "2012-06-13 01:49:34", updated_at: "2012-06-13 01:49:34"> 

1.9.3p194 :003 > last_post.comments_attributes = [{:id => 1, :author => "Bort"}] 
=> [{:id=>1, :author=>"Bort"}] 

1.9.3p194 :004 > last_post.changed? 
=> false 

1.9.3p194 :005 > last_post.save 
(0.1ms) begin transaction 
(0.7ms) UPDATE "comments" SET "author" = 'Bort', "updated_at" = '2012-06-13 01:51:05.032862' WHERE "comments"."id" = 1 
(250.1ms) commit transaction 
=> true 

1.9.3p194 :006 > last_post.updated_at 
=> Wed, 13 Jun 2012 01:49:34 UTC +00:00 

所以一定有什麼東西在其他情況下,是造成一個更新的被解僱。請檢查是否有可能這樣做的,也檢查,看看是否你的belongs_to方法不與:touch選項定義的任何callbacks。例如

belongs_to :event, :touch => true 
相關問題