rails/rails — pull request #12902 by martinemde (2013-11-15 18:17:27+00:00)
Title: Extend association support in PredicateBuilder AR:B.where to include has_many

This pull request depends on Pull Request rails/rails#12873. The rational is this:

ActiveRecord supports calling `where()` with hash arguments of the form `where(belongs_to_association: <#ActiveRecord::Base ...>)`. We even support adding the polymorphic class name from the association using the object. If we've already decided to support association names in where queries then we should support it fully instead of generating invalid SQL for some associations and some values.

Adding support for these association keys is straight forward and doesn't add any computational complexity to the PredicateBuilder since every key in the conditions hash already gets `reflect_on_association` called on it. This just takes one step more by supporting most association types.

This change is summarized as follows, in addition to the pull request #12873 above (the related commit is included herein).

**Description:** In addition to belongs_to associations, support for `where()` queries that use `has_many` association names.

Support for association names in `where` queries previously worked for `belongs_to` associations, but not for `has_many` associations. The SQL generated for `has_many` queries would actually be very confusingly wrong, using the wrong table and column entirely.

Given:

class Author < ActiveRecord::Base
has_many :posts
end

Existing ActiveRecord on master supports the behavior as follows:

authors_of_published_posts = Author.where(posts: { id: Post.where(published: true) }).joins(:posts)

This pull request adds support for this style of where conditions, thus filling out the support for association names in queries.

authors_of_published_posts = Author.where(posts: Post.where(published: true)).joins(:posts)