Skip to content

Commit

Permalink
pass correct object type to association reflection
Browse files Browse the repository at this point in the history
This is to make the association relation receive the expected parameter
(a AR instance, not its class).
  • Loading branch information
formigarafa committed Jan 11, 2017
1 parent 59dfb0e commit 3da8bcc
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
Expand Up @@ -35,12 +35,12 @@ def join_table_name
join_table_name.to_s
end

def association_relation
def association_relation(related_instance)
relation = associated_class.all

if reflection.scope
# Source: AR::Associations::AssociationScope#eval_scope
relation.instance_exec(subject, &reflection.scope)
relation.instance_exec(related_instance, &reflection.scope)
else
relation
end
Expand Down
Expand Up @@ -5,14 +5,18 @@ module AssociationMatchers
# @private
class ModelReflector
delegate :associated_class, :through?, :join_table_name,
:association_relation, :polymorphic?, :foreign_key,
:polymorphic?, :foreign_key,
:association_foreign_key, to: :reflection

def initialize(subject, name)
@subject = subject
@name = name
end

def association_relation
reflection.association_relation(subject)
end

def reflection
@reflection ||= reflect_on_association(name)
end
Expand Down
Expand Up @@ -95,10 +95,25 @@
person_model = define_model(:person, country_id: :integer) do
belongs_to :country, -> { where(mood: 'nice') }
end
person_instance = person_model.new(spirit: 'nice')
delegate_reflection = person_model.reflect_on_association(:country)
reflection = described_class.new(delegate_reflection)

actual_sql = reflection.association_relation.to_sql
actual_sql = reflection.association_relation(person_instance).to_sql
expected_sql = Country.where(mood: 'nice').to_sql
expect(actual_sql).to eq expected_sql
end

it 'executes the block in the context of an empty scope parametrised by association source' do
define_model(:country, mood: :string)
person_model = define_model(:person, country_id: :integer, spirit: :string) do
belongs_to :country, -> (person) { where(mood: person.spirit) }
end
person_instance = person_model.new(spirit: 'nice')
delegate_reflection = person_model.reflect_on_association(:country)
reflection = described_class.new(delegate_reflection)

actual_sql = reflection.association_relation(person_instance).to_sql
expected_sql = Country.where(mood: 'nice').to_sql
expect(actual_sql).to eq expected_sql
end
Expand All @@ -113,7 +128,7 @@
delegate_reflection = person_model.reflect_on_association(:country)
reflection = described_class.new(delegate_reflection)

actual_sql = reflection.association_relation.to_sql
actual_sql = reflection.association_relation(person_model).to_sql
expected_sql = Country.all.to_sql
expect(actual_sql).to eq expected_sql
end
Expand Down

0 comments on commit 3da8bcc

Please sign in to comment.