A has_and_belongs_to_many association using :finder_sql with interpolation is only evaluated once per class. This bug becomes evident when the interpolated sql query contains a call to an instance method (like #id()).
Without this patch, ActiveRecord caches the SQL query after the first interpolation, making all subsequent calls to the same association (even on different instances) use the same query string. The patch provided causes the interpolation to occur with each call to the association. Test case included.
For example, when post.categories is a has_and_belongs_to_many association defined with :finder_sql that contains a call to #{id}:
categories = Post.find(1).categories
categories == Post.find(2).categories
=> true
After the patch:
categories = Post.find(1).categories
categories == Post.find(2).categories
=> false