touch

 

class Article < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :article
end

 

当你对comment进行操作时,会自动更新comment的时间戳,但不会更新article的时间戳。

 

如果你使用touch(rails 2.3.3)的话,comment对应的article的时间戳也会被更新。

 

class Article < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  # Make create/update/deletes of a comment mark its
  # parent article as updated
  belongs_to :article, :touch => true
end

# Adding a new comment marks the article as being updated
article.updated_at #=> "Sun, 11 Apr 2010 07:54:06 UTC +00:00"
article.comments.create(:body => "New comment")
article.updated_at #=> "Sun, 11 Apr 2010 07:54:30 UTC +00:00"

# Same for updates/deletes
article.comments.first.destroy
article.updated_at #=> "Sun, 11 Apr 2010 07:55:01 UTC +00:00"

 

如果你不是使用的默认的updated_at或者updated_on,你也可以指定需要更新的字段。

 

class Article < ActiveRecord::Base
  has_many :comments
  validates_presence_of :last_updated_at  # non-standard
end

class Comment < ActiveRecord::Base
  belongs_to :article, :touch => :last_updated_at
end

# Adding a new comment marks the article as being updated
article.last_updated_at #=> "Sun, 11 Apr 2010 07:55:06 UTC +00:00"
article.comments.create(:body => "New comment")
article.last_updated_at #=> "Sun, 11 Apr 2010 07:55:20 UTC +00:00"

 

你还可以直接执行touch方法实现同样的功能。

 

article.updated_at #=> "Sun, 11 Apr 2010 07:56:06 UTC +00:00"
article.touch
article.updated_at #=> "Sun, 11 Apr 2010 07:56:08 UTC +00:00"

 

你可能感兴趣的:(sun,ActiveRecord)