Updating an array of tag's timestamps
Will this method update every tag's updated_at timestamp from Acts_As_Taggable_On's tag_list array?
def update_tag_timestamp
self.tag_list.each do |tag|
tag.update_attribute(:updated_at, Time.current)
end
end
I'm using Ruby 1.9.2, Rails 3.0.7, and the 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(:up开发者_运维百科dated_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: (simplified with 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: (this doesn't work, I can create as many tags as I want. The limit is ignored)
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
use tag.touch(:updated_at)
instead of update_attribute
touch
is there for this exact case
精彩评论