【发布时间】:2019-07-21 17:40:26
【问题描述】:
我有一个模型说Book,它具有以下作用域函数:
scope :author, lambda { |author|
return where(nil) unless author.present?
joins(:author).where('author.id' => author)
}
这可以过滤只有一个作者值的书籍。我想要做的是,我从一个 JavaScript 文件中传递了一个数组,它是一个作者列表,例如:["harry", "doyle", "alex", "parrish"],我希望能够找到所有拥有这些作者的所有书籍(所以一个 OR 查询这里)。请注意,每本书可以有多个作者。
我尝试了以下功能,但它只是给了我所有的书,而不是像我上面所说的那样正确过滤。
scope :authors_multiple, lambda { |authors|
@results = Book
authors.each do |auth|
@results = @results.author(auth)
end
return @results
}
模型作者(摘录):
class Author < ApplicationRecord
has_and_belongs_to_many :books, uniq: true
....
模型书(摘录):
class Book < ApplicationRecord
has_and_belongs_to_many :authors, uniq: true
....
请您帮助我了解我做错了什么或正确的方法。提前致谢。
【问题讨论】:
-
你能添加你的关系和架构吗?书有单数关系
author。您如何为一本书存储多个作者?
标签: javascript ruby-on-rails ruby input-filtering