我正在与iPhone应用程序同步数据,因此,重要的是要知道哪些记录已经“实际”更新了,哪些记录没有“更新”。我有一个带有RelatedLink关联的事件模型:

在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字段)时,我感觉很好……事件模型上没有任何更新。但是,如果我在RelatedLink字段中输入一个url,则会更新事件对象上的“updated_at”。
UPDATE "events" SET "updated_at" = '2011-05-30 15:27:03.228435' WHERE "events"."id" = 1791

应该这样吗?我可以阻止它被标记为脏并进行更新吗?

最佳答案

如果父模型的属性不变,那么记录就不会被认为是肮脏的,并且updated_at也不应改变。以这个为例(Rails 3.2.3)

发布模型

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

因此,在您的情况下,肯定还有其他原因会导致对Event触发更新。检查是否有任何callbacks可能正在执行此操作,并检查belongs_to选项是否未定义您的:touch方法。例如
belongs_to :event, :touch => true

10-08 00:25