如何创建一个简单的活动流?

时间:2011-10-10 20:53:19

标签: ruby-on-rails-3 model render helper

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

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))]

然后在模板方面对此进行评估?

1 个答案:

答案 0 :(得分:2)

这是我关于你案件的第一个协会。也许它足以激励你:)

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