此方法是否会更新Acts_As_Taggable_On的tag_list数组中每个标记的updated_at时间戳?
def update_tag_timestamp
self.tag_list.each do |tag|
tag.update_attribute(:updated_at, Time.current)
end
end
我正在使用Ruby 1.9.2,Rails 3.0.7和Acts_As_Taggable_On gem。
post.rb:
class Post < ActiveRecord::Base
after_create :update_tag_timestamp, :destroy_old_posts
acts_as_taggable
validates :name, :allow_blank => true,
:length => { :maximum => 64 }
validates :title, :presence => true,
:length => { :maximum => 64 }
validates :content, :presence => true,
:length => { :maximum => 1024 }
validates :tag_list, :presence => true,
:length => { :maximum => 24 }
has_many :comments, :dependent => :destroy
#belongs_to :tag#, :dependent => :destroy
attr_accessible :name, :title, :content, :tag_list
# Finds last three comments for a message.
def firstcomments
comments.find(:all, :limit => 3, :order => 'updated_at DESC').reverse
end
protected
# Updates the timestamps of the Parent Post's tag_list array
def update_tag_timestamp
self.tag_list.each do |tag|
tag.update_attribute(:updated_at, Time.current)
end
end
def destroy_old_posts
self.tag_list.each do |tag|
posts = Post.tagged_with(tag, :order => 'updated_at DESC')
posts[100..-1].each {|p| p.destroy } if posts.size >= 100
end
end
end
comment.rb :(简化为touch
)
class Comment < ActiveRecord::Base
validates :commenter, :allow_blank => true,
:length => { :maximum => 64 }
validates :body, :presence => true,
:length => { :maximum => 1024 }
after_create :destroy_old_comments
belongs_to :post, :touch => true
attr_accessible :commenter, :body
protected
# Destroys oldest comment after limit is reached
def destroy_old_comments
comments = post.comments(:order => 'updated_at ASC').reverse
comments[100..-1].each {|c| c.destroy } if comments.size >= 100
end
end
tag.rb :(这不起作用,我可以创建任意数量的标签。忽略限制)
class Tag < ActiveRecord::Base
after_create :destroy_old_tags
has_many :posts, :dependent => :destroy
protected
def destroy_old_tags
tags = Tag.all(:order => 'updated_at DESC')
tags[100..-1].each {|t| t.destroy } if tags.size >= 100
end
end
答案 0 :(得分:1)
使用tag.touch(:updated_at)
代替update_attribute
touch