A question about searching associations not a bug
scopethis opened this issue · 1 comments
Hi, I'm just getting my head around pg_search and I have a question regarding associations.
Given the following simple setup
class Book < ActiveRecord::Base
has_many :reviews
end
class Review < ActiveRecord::Base
belongs_to :book
end
There is no joining table in this scenario. Just two tables: books and reviews.
If I wanted to grab all reviews and their associated book. I could do something like
Review.joins(:book).select('reviews.*', 'books.*')
This should return a list of repeated book names with their review.
I assumed I would be able to do something like:
class Review < ActiveRecord::Base
belongs_to :book
pg_search_scope :search,
against: {comment: 'A'},
associated_against: {
book: {name: 'B'}
},
using: { tsearch: { dictionary: 'english' } }
end
Review.joins(:book).select('reviews.*', 'books.*')
.search('Harry Potter and the Deathly Hallows is a page turner.')
Is that possible? Or have i missed something?
Scopes from pg_search are chainable, just like any other scope, so I think the general answer to your question is yes.
It would be more conventional to do this, I would think:
Review.search('Harry Potter and the Deathly Hallows is a page turner.').includes(:book)
And you'd get Review
records where you could call Review#book
to retrieve the book.
e.g. (a rough sketch)
reviews = Review.search('Harry Potter and the Deathly Hallows is a page turner.').includes(:book)
review = reviews.first
review # => <#Review text="I think that Harry Potter and the Deathly Hallows is a real page turner, don't you agree?">
review.book #=> <#Book title="Harry Potter and the Deathly Hallows">