rails/rails — pull request #14161 by konukhov (2014-02-22 20:05:07+00:00)
Title: 'Where' (.not) with polymorphic association in AR::Relation bug fix

Hi!

While working on a Rails 4 app I ran into a nasty bug that builds wrong queries for polymorphic associations.

Here's an example:

```ruby
class Like < ActiveRecord::Base
belongs_to :likeable, polymorphic: true
end
```

In current versions of Rails it works this way:
```ruby
Like.where.not(likeable: Post.first).to_sql
=> "... where (likes.likeable_type != 'Post') and (likes.likeable_id != 1)"
```
This query finds all likes whose likeables are not a 'Post' and their ids are not 1. This behavior is wrong.

The idea is to use parentheses around both polymorphic conditions to treat them as a unified expression.

Here's how it works in this PR:

```ruby
Like.where(likeable: Post.first).to_sql
=> "... where (likes.likeable_type = 'Post' and likes.likeable_id = 1)"

Like.where.not(likeable: Post.first).to_sql
=> "... where (not (likes.likeable_type = 'Post' and likes.likeable_id = 1))"
```