Skip to content

Commit

Permalink
Fix belong_to used with polymorphic association
Browse files Browse the repository at this point in the history
For a polymorphic belongs_to association, the association doesn't
actually point to a class, it points to a concept, so we can't check
that the model it points to exists.
  • Loading branch information
mcmire committed Apr 12, 2014
1 parent bb1aa83 commit c590a60
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 4 deletions.
4 changes: 2 additions & 2 deletions lib/shoulda/matchers/active_record/association_matcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def have_and_belong_to_many(name)

class AssociationMatcher # :nodoc:
delegate :reflection, :model_class, :associated_class, :through?,
:join_table, to: :reflector
:join_table, :polymorphic?, to: :reflector

def initialize(macro, name)
@macro = macro
Expand Down Expand Up @@ -188,7 +188,7 @@ def matches?(subject)
@subject = subject
association_exists? &&
macro_correct? &&
class_exists? &&
(polymorphic? || class_exists?) &&
foreign_key_exists? &&
class_name_correct? &&
autosave_correct? &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ def associated_class
reflection.klass
end

def polymorphic?
reflection.options[:polymorphic]
end

def through?
reflection.options[:through]
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module ActiveRecord # :nodoc:
module AssociationMatchers
class ModelReflector
delegate :associated_class, :through?, :join_table,
:association_relation, to: :reflection
:association_relation, :polymorphic?, to: :reflection

def initialize(subject, name)
@subject = subject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
end

it 'accepts a polymorphic association' do
define_model :parent
define_model :child, parent_type: :string, parent_id: :integer do
belongs_to :parent, polymorphic: true
end
Expand Down

0 comments on commit c590a60

Please sign in to comment.