I have Page and Paragraph models with a has_and_belongs_to_many relation. Given a paragraph_id, I'd like to get all matching pages. e.g.:
pages = Paragraph.find(paragraph_id).pages.all
However, this takes two queries. It can be done in one query:
SELECT "pages".* FROM "pages"
INNER JOIN "pages_paragraphs" ON "pages_paragraphs"."page_id" = "pages"."id"
WHERE "pages_paragraphs"."paragraph_id" = 123
But can this be done without
- using find_by_sql
- without modifications to the page_paragraphs table (e.g. adding an id).
Update:
My page model looks like this:
class Page < ActiveRecord::Base
has_and_belongs_to_many :paragraphs, uniq: true
end