2017-06-29 86 views
0

我想讓我的應用程序的用戶有機會從他們的微博中刪除不需要的微博。默認情況下,微觀柱飼料是從遵循用戶做出的用戶自己的微柱加上微觀柱:減去兩個ActiveRecord ::關係對象

def feed 
    following_ids = "SELECT followed_id FROM relationships 
        WHERE follower_id = :user_id" 
    Micropost.where("user_id IN (#{following_ids}) 
        OR user_id = :user_id", user_id: id) 
end 

我創建了一個模型Quarantine,用戶和不必要的微觀柱相關聯。然後,我找了個ActiveRecord::Relation方法,讓我從上面where減去以下where

microposts_ids = "SELECT micropost_id FROM quarantines 
        WHERE user_id = :user_id" 

Micropost.where("micropost_id IN (#{microposts_ids})", user_id: id) 

我找不到對應於-陣列操作的任何方法。不過,我在#1的問題找到方法mergeCombine two ActiveRecord::Relation objects,即,據我瞭解,將使我鏈wheres如下:

Micropost.where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id).merge(Micropost.where.not("micropost_id IN (#{microposts_ids})", user_id: id)) 

不同的是,我改變了第二wherewhere.not
此解決方案的問題是where.not會加載所有未隔離的Micropost,這對於數據庫來說是一項比加載隔離的微博更重的作業。 merge方法是否有其他解決方案,例如從原始供稿中減去隔離的微博?

回答

1

對於特定user

microsposts_not_to_show = Micropost.joins(:quarantines).where("quarantines.user_id" => user.id) 
all_microposts = Micropost.where("user_id" => user.id) + Micropost.joins(:user => : relationships).where("relationships.follower_id" => user.id) 
microposts_to_show = all_microposts - microposts_not_to_show 
+0

我不確定'microposts_not_to_show'的定義是否正確:它應該返回一個Micropost對象而不是隔離對象:其中的參數包含一個隔離對象。 – Asarluhi

+0

我們正在加入表格。在使用select方法明確指定之前,它不會顯示Quarantine對象。 – moyinho20

+0

我收到以下警告:'ActiveRecord :: StatementInvalid:PG :: UndefinedColumn:錯誤:列quarantines.user_id不存在'。 – Asarluhi

0

對於導軌5它可能看起來像:

class User < ApplicationRecord 
    has_many :relationships 
    # ... 
    def feed 
    Micropost 
     .where(user_id: relationships.select(:followed_id)) 
     .or(Micropost.where(user_id: id)) 
     .where.not(id: Quarantine.select(:micropost_id).where(user_id: id)) 
    end 
end 

feed返回relation產生ONY一個DB請求,並且可以與附加的濾波被鏈接,訂貨 - 無論你需要什麼。