Given a blog where
Person <->> Comment
Comment <<-> Article
Article <<->> Person (an article may be written by more than one
person - though I don’t think this point is important)
I would like to find all the Comments written by Frank associated with
Articles written by Bob.
In person I have
scope :by, lambda { |name| joins(:person).merge(Person.where(:name
=> name)) }
scope :on_article_by, lambda { |name| joins(:article
=> :people).merge(Person.where(:name => name)) }
So I can find
Comment.by(“Frank”) which works
and
Comment.on_article_by(“Bob”) works
However
Comment.by(“Frank”).on_article_by(“Bob”) does not work.
I get something like:
SELECT “comments”.* FROM “comments”
INNER JOIN “people” ON “people”.“id” = “comments”.“person_id”
INNER JOIN “articles” ON “articles”.“id” = “comments”.“article_id”
INNER JOIN “article_people” ON “articles”.“id” =
“article_people”.“article_id”
INNER JOIN “people” “authors_articles” ON “authors_articles”.“id” =
“article_people”.“person_id”
WHERE (“people”.“name” = ‘Bob’)
Two or more things are happening, here:
- The reference to Frank is completely missing.
- The reference to Bob is being applied to the comment author, NOT
the article author.
What am I doing wrong?
Or
What is arel doing wrong?
And
How do I make it right?