This project is archived and is in readonly mode.

#3684 ✓duplicate
Tatsuya Ono

find creates wrong SQL when you set "has_one :through" association on :join option

Reported by Tatsuya Ono | January 11th, 2010 @ 11:33 PM

I ran into an issue on has_one :through.

First patch(test_join_has_many_throgh.diff) adds test cases to reproduce the issue.

When you define an association like the following ...

class Author
   has_many :author
end
class Post
   belongs_to :author
end
class Comment
   belongs_to :post
   has_one :post_author, :through=>:post, :source=>:author
end

And if you write the code like the following ...

comments = Comment.find :all, :conditions=>["authors.name = ?", "David"], :joins=>[:post_author]

It creates a SQL like this and you will get an exception.

SELECT "comments".* FROM "comments"
INNER JOIN "posts" ON ("comments"."id" = "posts"."post_id")    # <= Here is the problem
INNER JOIN "authors" ON ("authors"."id" = "posts"."author_id")  
WHERE (authors.name = 'David')

Since through_reflection is not :has_many but :belongs_to, the second line should be comments.post_id=posts.id.

The second patch(fix_join_has_one_through.diff) fixes this issue; it checks through_reflection.macro and creates a correct SQL in association.rb. It also includes test cases defined on the first patch and I checked the tests are passed as well as other existing tests.

(The patches are made against 2-3-stable.)

Comments and changes to this ticket

Create your profile

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

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages