#699 ✓resolved
ash.gti

Improper join generation on associations

Reported by ash.gti | December 7th, 2008 @ 05:41 PM

Doing nested association conditions on a find results in an improper join statement.

my attacked file has references to the classes I am using

You can do this: User.all(User.posts.title => "Hi")

and it works just fine, it generates:

SELECT "users"."id", "users"."name" FROM "users" INNER JOIN "posts" ON ("users"."id" = "posts"."user_id") WHERE ("posts"."title" = 'Hi') ORDER BY "users"."id"

but if you try to reference a nested association like: User.all(User.posts.comments.from => "John")

it generates:

SELECT "users"."id", "users"."name" FROM "users" INNER JOIN "posts" ON ("users"."id" = "posts"."user_id") INNER JOIN "posts" ON ("posts"."id" = "comments"."post_id") WHERE ("comments"."from" = 'John') ORDER BY "users"."id"

Which is not joining the comments table and results in an improper SQL statement.

It should be:

SELECT "users"."id", "users"."name" FROM "users" INNER JOIN "posts" ON ("users"."id" = "posts"."user_id") INNER JOIN "posts" ON ("users"."id" = "posts"."user_id") INNER JOIN "comments" ON ("posts"."id" = "comments"."post_id WHERE ("comments"."from" = 'John') ORDER BY "users"."id"

Also note that the first JOIN has the wrong conditions. They were not associating the posts to the users.

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

People watching this ticket

Pages