Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 抓取所有用户';s现职_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails 抓取所有用户';s现职

Ruby on rails 抓取所有用户';s现职,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我的active_posts实例方法在我的User模型上不起作用 我正在抓取一个用户记录,然后对于该记录,我需要加入博客和帖子表,然后通过帖子的活动属性进行过滤,以便只为该用户返回活动的帖子 class User < ApplicationRecord has_many :blogs has_many :posts, through: :blogs def active_posts joins(blogs: :posts).merge(Post.active).dis

我的
active_posts
实例方法在我的
User
模型上不起作用

我正在抓取一个
用户
记录,然后对于该记录,我需要加入
博客
帖子
表,然后通过帖子的
活动
属性进行过滤,以便只为该
用户返回活动的
帖子

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
下面是错误:

命名者 用户记录上未定义的方法“联接”


刚刚意识到我的错误

只需在
active\u posts
方法中调用
posts.active

def active_posts
  posts.active
end

联接
用于集合。因此,您可以在模型中的类方法上使用
联接
,而不是在实例方法中使用。简单的错误。

刚刚意识到我的错误

只需在
active\u posts
方法中调用
posts.active

def active_posts
  posts.active
end

联接
用于集合。因此,您可以在模型中的类方法上使用
联接
,而不是在实例方法中使用。简单错误。

joins
是类方法-您从实例调用它。
joins
是类方法-您从实例调用它。