rails/rails — pull request #14969 by bigxiang (2014-05-04 11:15:14+00:00)
Title: Fix 2 wrong behaviors for has_and_belongs_to_many association in Rails 4.0

**Fix wrong `size` result after built `has_and_belongs_to_many` association and kept the assciation unloaded.**

It was reported in #14914

```ruby
class User < ActiveRecord::Base
has_and_belongs_to_many :comments
end

class Comment < ActiveRecord::Base
has_and_belongs_to_many :users
end

user = User.create
user.comments.build

user.comments.size #should be 1, but be 2
```
The reason is that `count_records` method in `has_and_belongs_to_many_association.rb` just loads the association and fetches the size again, it repeatly calculates the unloaded new objects, but `has_many_association.rb` doesn't. So I just copied the method from `has_many_association.rb` and removed `counter_cache` statement.

**Fix wrong `clear` behavior when `has_and_belongs_to_many` association has scopes and hasn't been loaded.**

```ruby
class User < ActiveRecord::Base
has_and_belongs_to_many :comments
has_and_belongs_to_many :scoped_comments,
-> { where(attr: 'attr') }
end

class Comment < ActiveRecord::Base
has_and_belongs_to_many :users
end

# should delete scoped comments only,
# but it deletes all records
User.first.scoped_comments.clear
```

The reason is that `delete_records` method in `has_and_belongs_to_many_association.rb` doesn't calculate scopes. The old test case uses `size` method first, it loads the association and can't present this problem. The new test case uses `clear` method directly to indicate the problem. I added a block of code in `delete_records` in order to make sure that scopes are calculated correctly.