簡體   English   中英

Rails新聞提要以發表評論

[英]Rails news feed for comments

我更新了問題,因為我將以下位置和用戶組合到一個多態模型中。

因此,我正在嘗試為應用中的評論創建新聞提要。

我有一個用戶模型,一個用於跟蹤位置和用戶的模型。 然后我有一個評論模型。

如何從用戶關注的用戶的評論和用戶關注的位置的評論中收集這些評論?

我需要對它進行分頁,並按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語句) 如何在SQL SELECT中執行IF ... THEN?

我仍然不確定如何編寫此查詢,但我認為CASE語句可能會有所幫助。

如果我正確地收集了您的問題,那么您可能會在模型中看到以下內容:

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)

隨着這變得越來越復雜,也將變得越來越復雜,請研究范圍和合並。 可能將此方法拉到某個地方的搜索類中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM