Skip to content

Commit

Permalink
Merge pull request thoughtbot#992 from formigarafa/fix-association-re…
Browse files Browse the repository at this point in the history
…lation

pass correct object type to association reflection
  • Loading branch information
alyssais committed Mar 12, 2017
2 parents 9ba960e + 66d5b5d commit fed565f
Show file tree
Hide file tree
Showing 3 changed files with 25 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,13 +95,29 @@
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 'pass instance of association source to block' do
spy = spy('spy')
define_model(:country, mood: :string)
person_model = define_model(:person, country_id: :integer) do
belongs_to :country, ->(person) { spy.who(person) }
end
person_instance = person_model.new(spirit: 'nice')
delegate_reflection = person_model.reflect_on_association(:country)
reflection = described_class.new(delegate_reflection)

reflection.association_relation(person_instance)

expect(spy).to have_received(:who).with(person_instance)
end
end

context 'when the scope is nil' do
Expand All @@ -113,7 +129,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 fed565f

Please sign in to comment.