2011-04-23 93 views
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 
+0

''從acts_as_taggable_on' taggings'表不包含'updated_at'屬性可言。 – 2011-04-23 07:07:09

+0

我將updated_at和created_at列添加到了我的標記模型。我希望能夠在最後一次通過Post模型進行更新時對標籤進行排序。 – BasicObject 2011-04-23 07:28:02

+0

請展示您的模型。 – 2011-04-23 07:30:29

回答

1

使用tag.touch(:updated_at)代替update_attribute

touch是有這個確切的情況下