【问题标题】:Ruby on Rails: Create an Activity Feed by Sum two ModelRuby on Rails:通过对两个模型求和创建活动提要
【发布时间】:2017-10-24 06:06:01
【问题描述】:

我正在尝试创建一个混合两个模型(发布 + 赞)的活动提要。活动提要同时显示当前用户和关注用户发布 + 点赞。

我在用户模型中创建 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 等...并且一切正常。

以这种方式汇总 Posts 和 Likes 是否正确?

【问题讨论】:

  • 在这种情况下使用常量肯定是不正确的。

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


【解决方案1】:

我会尽量充分利用 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,并将每个操作的责任委托给最相关的模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2011-08-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多