I have a model say Book which has the following scope function:
scope :author, lambda { |author|
return where(nil) unless author.present?
joins(:author).where('author.id' => author)
}
This can filter the Books with only ONE author value. What I want to do is that I am passed a array from a JavaScript file which is a list of authors for example: ["harry", "doyle", "alex", "parrish"] and I want to be able to find all the books who has ANY of these authors (so an OR query here). Note each book can have multiple authors.
I have tried the following function but it simply gives me all the books rather than filtering correctly as I stated above.
scope :authors_multiple, lambda { |authors|
@results = Book
authors.each do |auth|
@results = @results.author(auth)
end
return @results
}
model Author (extract):
class Author < ApplicationRecord
has_and_belongs_to_many :books, uniq: true
....
model Book (extract):
class Book < ApplicationRecord
has_and_belongs_to_many :authors, uniq: true
....
Can you please help me understand what I am doing wrong or what may be the right way to do it. Thanks in advance.
or
This assumes that an Author has many Books. You can learn more about model associations here: https://guides.rubyonrails.org/association_basics.html