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
4

1 回答 1

1

使用tag.touch(:updated_at)而不是update_attribute

touch是否有这种确切的情况

于 2011-04-23T07:31:34.253 回答