2016-11-17 46 views
1

我的active_posts的實例方法不適用於我的User模型。抓住所有用戶的活動帖子

我抓住一個user記錄,那麼該記錄我需要加入blogsposts表,然後通過這篇文章的active屬性,以便只爲user返回活動posts過濾。

class User < ApplicationRecord 
    has_many :blogs 
    has_many :posts, through: :blogs 

    def active_posts 
    joins(blogs: :posts).merge(Post.active).distinct 
    end 
end 

class Blog < ApplicationRecord 
    belongs_to :user 
    has_many :posts 
end 

class Post < ApplicationRecord 
    belongs_to :blog 
    belongs_to :user, through: :blog 

    scope :active, -> {where(active: true} 
end 

我運行以下命令:

User.first.active_posts 

這裏是錯誤:

NoMethodError Undefined method 'joins' on the user record

回答

0

剛剛意識到我的錯誤。

只需在active_posts方法內調用posts.active即可。

def active_posts 
    posts.active 
end 

joins用於收集。所以你可以在你的模型的類方法上使用joins,而不是在實例方法中。簡單的錯誤。

+1

'joins'是一個類方法 - 你從一個實例調用它。 – ReggieB