【问题标题】:Rails news feed for comments用于评论的 Rails 新闻提要
【发布时间】:2014-10-14 19:55:23
【问题描述】:

我更新了问题,因为我将以下位置和用户组合成一个多态模型。

所以我正在尝试在我的应用中为 cmets 制作新闻提要。

我有一个用户模型,一个用于跟踪位置和用户的模型。然后我有一个 cmets 模型。

如何从用户关注的用户那里获取 cmets 和从用户关注的位置获取 cmets 并将它们放在一起?

我需要对它进行分页以及按 created_at 时间戳排序(首先显示最新的)。

这是我的迁移的样子

create_table :comments do |t|
  t.text :text
  t.integer :user_id
  t.integer :commentable_id
  t.string :commentable_type

create_table :follows do |t|
  t.integer :user_id
  t.integer :followable_id
  t.string :followable_type

这就是我的模型的样子

class User < ActiveRecord::Base
    has_many :comments, as: :commentable
end

class Comment < ActiveRecord::Base
    belongs_to :commentable, polymorphic: true
end

更新: 我在 sql 中发现了一个叫做 CASE 语句的东西(比如 if 语句)How do I perform an IF...THEN in an SQL SELECT?

我仍然不确定如何编写此查询,但我认为 CASE 语句可能会有所帮助。

【问题讨论】:

  • 问题是什么?
  • 我编辑了这个问题,抱歉不清楚
  • 用户可以评论位置以外的任何内容吗?如果不是,则不需要多态关系。不过,你应该有一个跟随的多态关系,这样你就有一个像这样的模型:class Follow &lt; ActiveRecord::Base belongs_to :user belongs_to :followable, polymorphic: true
  • 是的,他们可以评论其他事情,这就是它具有多态性的原因。我没有想到有以下多态性。如果我这样做,那么查询会是什么样子?我想这种方式也简单得多。谢谢!
  • 请发布您的所有模型和 schema.rb。

标签: sql ruby-on-rails ruby activerecord ruby-on-rails-4


【解决方案1】:

如果我正确地收集了你的问题,你可能会看到这样的模型:

class User < ActiveRecord::Base

  has_many :comments, as: :commentable, dependent: :nullify

  has_many :follows, dependent: :destroy
  has_many :followed_users, class_name: 'Follow', conditions: {followable_type: 'User'}
  has_many :followed_locations, class_name: 'Follow', conditions: {followable_type: 'Location'}

  has_many :followers, as: :followable, dependent: :destroy

end

在您的控制器中,您可能会看到如下内容:

# See all comments made by those you follow (and yourself)
# See all comments made on locations you follow
# See all comments made on users you follow
@comments = Comment.where(
  'user_id in (:followed_user_ids) or (commentable_type = 'Location' and commentable_id in (:followed_location_ids)) or (commentable_type = 'User' and commentable_id in (:followed_user_ids))',
  { 
    followed_user_ids: current_user.followed_users.pluck(:user_id) | [current_user.id], 
    followed_location_ids: current_user.followed_locations.pluck(:location_id)
  }
).paginate(page: params[:page]).order(created_at: :desc)

随着这变得越来越复杂,它会变得更加复杂,请查看范围和合并。可能会将这个方法拉到某个搜索类中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2018-09-15
    • 2013-06-20
    • 1970-01-01
    相关资源
    最近更新 更多