Ruby on rails 返回作者的书籍数组,多对多关系

Ruby on rails 返回作者的书籍数组,多对多关系,ruby-on-rails,many-to-many,Ruby On Rails,Many To Many,我有两个模型,作者和书,还有一个中间桌子。这是一种多对多的关系。我的任务是创建一个变量@myBooks,该变量返回作者拥有的所有书籍的数组。但是,我们将在会话中按作者id进行搜索[:user\u id] class middleItem < ApplicationRecord belongs_to :author belongs_to :book end class Book < ApplicationRecord has_many :middleItem has_

我有两个模型,作者和书,还有一个中间桌子。这是一种多对多的关系。我的任务是创建一个变量@myBooks,该变量返回作者拥有的所有书籍的数组。但是,我们将在会话中按作者id进行搜索[:user\u id]

class middleItem < ApplicationRecord
  belongs_to :author
  belongs_to :book
end

class Book < ApplicationRecord
  has_many :middleItem
  has_many :author, through: :middleItem
end

class Author < ApplicationRecord
  has_many :middleItem
  has_many :books, through: :middleItem
end
编辑: 作者:(1)莎士比亚,(2)奥威尔 书籍:(1)罗密欧与朱丽叶,(2)哈姆雷特,(3)动物农场

中间表格:(1,1)、(1,2)、(2,3)


@myBooks应该是:“romeo and juliet,hamlet”如果假设session[:user_id]是1,我认为解决这个问题的一个好方法是使用
范围,您可以在
book
模型中定义范围,如下所示:

scope:search\u by\u author,->(author\u id){joins(:authors).where(author.arel\u table[:id].eq(author\u id)).distinct}
上述内容可以像这样使用:
Book.search by\u author(1)
,如果您确实需要数组而不是ActiveRecord结果,您可以将结果强制转换为数组:
Book.search by\u author(1)。to\u a


希望以上帮助!除了需要做一些工作的查询之外,我认为您的图书模型中有一个输入错误,应该是:authors不确定我是否理解其中的一些部分,但是完全基于您的代码
book.joins(:authors)。其中(authors:{id:session[:user\u id]})
就足够了。旁注:
map{x | x.any|db_attribute_here}
始终可以缩短为
pluck(:any|db_attribute_here)
感谢您的帮助。我试着让事情变得更清楚,检查edit@engineersmnky这个很好用,谢谢!一些建设性意见:1)您可以使用
Author.arel_属性(:id)
而不是
Author.arel_表[:id]
;2) 对于简单的用例,如equality
,其中(表名:{column\u name:value})
通常被认为比使用
Arel
更惯用;3)
+[]
是一种将
ActiveRecord::Relation
转换为
数组的笨拙方法,而不是使用.Thx作为注释@ngineersmnky,将编辑我的答案,因此更有用/更清晰,尽管我更喜欢使用arel_表方法Thx
Book.joins(:authors).joins(:middleItem).where(middleItem: {user_id: session[:user_id]}).distinct.map {|x| puts x.name}