2011-10-10 3 views
4

간단한 활동 스트림을 구현하려고합니다.간단한 활동 스트림을 만드는 방법은 무엇입니까?

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="https://stackoverflow.com/users/abc">abc</a> created a post <a href="https://stackoverflow.com/users/abc/posts/123">123</a></li> 
    <li>User <a href="https://stackoverflow.com/users/xyz">xyz</a> commented on post <a href="https://stackoverflow.com/users/abc/posts/123">123</a></li> 
</ul> 

(컨트롤러에서 여러 개의 쿼리가 아닌) 활동 모델을 채우는 것을 선호합니다. 나는 활동 채우기 위해 게시물과 댓글 모델 모두에 'after_create'훅을 추가 : 내가 등등 post_id를, 같은 경로와 링크를 만들어야 특별한 필드를 저장하는 생각

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

을하지만 나중에 추적하고 싶은 활동, 좋아하는 것, 싫어하는 것, 즐겨 찾기 등이있을 수 있으며 활동 설명을 만드는 유연한 방법이 필요합니다.

제 질문은 link_to를 활동 설명에 넣는 효율적인 방법은 무엇입니까? 나중에 평가할 헬퍼를 나열하는 C 스타일 printf 방법이 있습니까? 이런의

분류 :

설명 =? "사용자가 포스트에 댓글?"user_path (User.find (self.user_id)) post_path (Post.find (self.id))]

그리고 템플릿 측에서 이것을 평가 하시겠습니까?

+0

아마도 모델이 링크와 경로에 대해 아는 것이 좋지 않을 것입니다. –

+0

동의, 아마도 그 활동은 다형성 협회로서 더 잘 다뤄질 수 있습니다 ... – Homan

답변

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 
+0

그냥 호기심 - 사용자 모델에서 has_many ': Activities'또는 has_many ': Activitys'또는 Rail이 어떻게 든 차이를 알고 있습니까? – dsignr

+1

당신은 단수 복수형을 의미합니까? http://4loc.wordpress.com/2009/04/09/inflector-rails-pluralization/ 또는 http://edgeguides.rubyonrails.org/i18n.html#pluralization – abstraktor

+0

대단히 감사합니다! – dsignr

관련 문제