1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Only merge scopes with zero arity in has_many through

with dynamic conditions.

Fixes #16128

This bug was introduced in c35e438620
so it's present from 4.1.2-rc1 and after.

c35e438620
merges any relation scopes passed as proc objects to the relation,
but does *not* take into account the arity of the lambda.

To reproduce: https://gist.github.com/Agis-/5f1f0d664d2cd08dfb9b
This commit is contained in:
Agis- 2014-07-15 03:25:18 +03:00
parent 7422d2175d
commit 431f8e0119
6 changed files with 29 additions and 1 deletions

View file

@ -1,3 +1,10 @@
* Fix has_many :through relation merging failing when dynamic conditions are
passed as a lambda with an arity of one.
Fixes #16128
*Agis Anastasopoulos*
* Fixed the `Relation#exists?` to work with polymorphic associations.
Fixes #15821.

View file

@ -15,7 +15,11 @@ module ActiveRecord
scope = super
reflection.chain.drop(1).each do |reflection|
relation = reflection.klass.all
relation.merge!(reflection.scope) if reflection.scope
reflection_scope = reflection.scope
if reflection_scope && reflection_scope.arity.zero?
relation.merge!(reflection_scope)
end
scope.merge!(
relation.except(:select, :create_with, :includes, :preload, :joins, :eager_load)

View file

@ -4,6 +4,7 @@ require 'models/comment'
require 'models/developer'
require 'models/post'
require 'models/project'
require 'models/rating'
class RelationMergingTest < ActiveRecord::TestCase
fixtures :developers, :comments, :authors, :posts
@ -144,4 +145,16 @@ class MergingDifferentRelationsTest < ActiveRecord::TestCase
assert_equal ["Mary", "Mary", "Mary", "David"], posts_by_author_name
end
test "relation merging (using a proc argument)" do
dev = Developer.where(name: "Jamis").first
comment_1 = dev.comments.create!(body: "I'm Jamis", post: Post.first)
rating_1 = comment_1.ratings.create!
comment_2 = dev.comments.create!(body: "I'm John", post: Post.first)
rating_2 = comment_2.ratings.create!
assert_equal dev.ratings, [rating_1]
end
end

View file

@ -9,6 +9,7 @@ class Comment < ActiveRecord::Base
belongs_to :post, :counter_cache => true
belongs_to :author, polymorphic: true
belongs_to :resource, polymorphic: true
belongs_to :developer
has_many :ratings

View file

@ -46,6 +46,8 @@ class Developer < ActiveRecord::Base
has_many :audit_logs
has_many :contracts
has_many :firms, :through => :contracts, :source => :firm
has_many :comments, ->(developer) { where(body: "I'm #{developer.name}") }
has_many :ratings, through: :comments
scope :jamises, -> { where(:name => 'Jamis') }

View file

@ -198,6 +198,7 @@ ActiveRecord::Schema.define do
t.references :author, polymorphic: true
t.string :resource_id
t.string :resource_type
t.integer :developer_id
end
create_table :companies, force: true do |t|