Ruby on Rails:通过Sum two Model创建一个Activity Feed

时间:2017-10-24 06:06:01

标签: sql ruby-on-rails ruby database model-view-controller

我正在尝试创建一个混合两个模型的活动源(Post + Like)。活动源显示当前用户和后续用户Post + Like。

我在User模型中创建了feed方法(遵循MHartl教程)。

  def feed

    following_ids = "SELECT followed_id FROM relationships WHERE follower_id = :user_id"
    Posts = Post.where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id)
    Likes = Like.where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id)

    Posts + Likes

  end

在控制器中,我只需拨打@feed = current_user.feed.paginate等等......一切正常。

以这种方式对帖子和喜欢进行总结是否正确?

1 个答案:

答案 0 :(得分:0)

我会尝试从Rails模型中获得最大收益。

例如,following_ids可以由关系的范围或类方法返回:

class Relationship < ActiveRecord::Base

  scope :followed_ids, ->(user_id) { where(follower_id: user_id).pluck(:followed_id) }
  # or

  def self.followed_ids(user_id)
    where(follower_id: user_id).pluck(:followed_id)
  end
end

你基本上可以为Post做同样的事情:

class Post < ActiveRecord::Base
  scope :feed_for, ->(user_id, following_ids) { where(user_id: [user_id, *following_ids]) }
end

和喜欢:

class Like < ActiveRecord::Base
  scope :feed_for, ->(user_id, following_ids) { where(user_id: [user_id, *following_ids]) }
end

最后将其集成到您的用户模型中:

class User < ActiveRecord::Base

  def feed
    following_ids = Relationship.followed_ids(self.id)
    Post.feed_for(self.id, following_ids) + Like.feed_for(self.id, following_ids)
  end

end

尽量不要在Rails代码中使用原始sql,并将每个操作的责任委托给最相关的模型。