Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.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
Sql 2查询模型时加入_Sql_Ruby On Rails_Ruby On Rails 3_Rails Activerecord - Fatal编程技术网

Sql 2查询模型时加入

Sql 2查询模型时加入,sql,ruby-on-rails,ruby-on-rails-3,rails-activerecord,Sql,Ruby On Rails,Ruby On Rails 3,Rails Activerecord,我有一个方法,它返回属于该类别的所有类别和组书籍 def self.user_categories_list joins(:books). select('categories.id, categories.name, count(*) AS books_count'). group('categories.id, categories.name'). order('books_count DESC') end 请原谅我的问题,但我不确定如何加入users表以按类别获取属于某个用户的所有书籍,

我有一个方法,它返回属于该类别的所有类别和组书籍

def self.user_categories_list
joins(:books).
select('categories.id, categories.name, count(*) AS books_count').
group('categories.id, categories.name').
order('books_count DESC')
end
请原谅我的问题,但我不确定如何加入users表以按类别获取属于某个用户的所有书籍,或者是否可以按属于某个用户的book_id进行此操作

谢谢你的帮助


谢谢

我想你应该有一个where子句:

def self.user_categories_list(user)
  joins(:books).
  where('books.user_id = ?', user.try(:id) || user).
  select('categories.id, categories.name, count(*) AS books_count').
  group('categories.id, categories.name').
  order('books_count DESC')
end

注意:此代码假定您的图书型号在其表中具有
user\u id
属性。

您是指属于特定用户的图书吗?在这种情况下,您只需要制作这个“实例方法”,并将它作为一个用户实例调用为<代码> @ Ur.UrrEythOrthoReSists<代码>,并且可以考虑将它重命名为<代码> DEF类别>列表>代码>,这样就不必调用SO了。它本身就是一个类方法,它被用作<代码>用户。用户不是特定的用户。在上面的注释中,
@user=user.find(1)
1是用户id