1
此方法是否会更新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
''从acts_as_taggable_on' taggings'表不包含'updated_at'属性可言。 – 2011-04-23 07:07:09
我将updated_at和created_at列添加到了我的标记模型。我希望能够在最后一次通过Post模型进行更新时对标签进行排序。 – BasicObject 2011-04-23 07:28:02
请展示您的模型。 – 2011-04-23 07:30:29