1
我的active_posts
的實例方法不適用於我的User
模型。抓住所有用戶的活動帖子
我抓住一個user
記錄,那麼該記錄我需要加入blogs
和posts
表,然後通過這篇文章的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
'joins'是一個類方法 - 你從一個實例調用它。 – ReggieB