ruby-on-rails-3 – 如何创建简单的活动流?

我正在尝试实现一个简单的活动流.

Given that User abc creates a post 123
And User xyz comments on 123.  
Then user abc's activity stream should look something like:
<ul>
  <li>User <a href="/users/abc">abc</a> created a post <a href="/users/abc/posts/123">123</a></li>
  <li>User <a href="/users/xyz">xyz</a> commented on post <a href="/users/abc/posts/123">123</a></li>
</ul>

我更喜欢填充活动模型(而不是控制器中的多个查询).我在帖子和评论模型中添加了一个’after_create’钩子来填充活动:

class Post < ActiveRecord
  after_create do
    ActivityCreate(:user_id => self.user_id, :description => "created a post")
  end
end

我想过存储我需要创建路径和链接的特殊字段,比如post_id等,但我可能有更多我想要跟踪的活动,喜欢,不喜欢,收藏等等,我想要一种灵活的创建方式活动描述.

所以我的问题是,将link_to放入活动描述的有效方法是什么?是否有任何c风格的printf方式列出助手以便稍后评估?

有点像:

description = [“用户?在帖子上发表评论?”,user_path(User.find(self.user_id)),post_path(Post.find(self.id))]

然后在模板方面评估这个?

最佳答案 这是我关于你的案子的第一个关联.也许它足够激励你:)

class Activity < ActiveRecord::Base
  #this might be a comment or a post or something else
  belongs_to :changed_item, :polymorphic => true
  #who did it?
  belongs_to :user
  #what did he do?
  validates_presence_of :changes

  def msg
    #do fancy text generation
    if changes.new_record
      "#{user.name} created a #{changed_item.class}"
    else
      "#{user.name} changed #{changes.length} attributes of the #{changed_item.class} #{changed_item.title}"
    end
  end

  def initialize(model, user)
    #fetch changes and remember user and changed model
    self.changed_item = model
    self.user = user
    self.changes << model.changed_attributes.merge({:new_record => model.new_record?})
  end
end

class Post < ActiveRecord::Base
  after_save do
    #remember who to be blamed
    Activity.create(self, current_user)
  end
end

class User < ActiveRecord::Base
  #the users activities
  has_many :activities
end
点赞