Skip to content

Commit

Permalink
Add AssociationReflection#collection_association? which returns true …
Browse files Browse the repository at this point in the history
…if it's for a has_many or has_and_belongs_to_many association.
  • Loading branch information
alloy committed Jan 7, 2010
1 parent 1afa9fa commit f82adc7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
9 changes: 8 additions & 1 deletion activerecord/lib/active_record/reflection.rb
Expand Up @@ -252,10 +252,17 @@ def polymorphic_inverse_of(associated_class)
end
end

# Returns whether or not this association reflection is for a collection
# association. Returns +true+ if the +macro+ is one of +has_many+ or
# +has_and_belongs_to_many+, +false+ otherwise.
def collection_association?
[:has_many, :has_and_belongs_to_many].include?(macro)
end

private
def derive_class_name
class_name = name.to_s.camelize
class_name = class_name.singularize if [ :has_many, :has_and_belongs_to_many ].include?(macro)
class_name = class_name.singularize if collection_association?
class_name
end

Expand Down
9 changes: 9 additions & 0 deletions activerecord/test/cases/reflection_test.rb
Expand Up @@ -4,6 +4,7 @@
require 'models/company'
require 'models/company_in_module'
require 'models/subscriber'
require 'models/ship'
require 'models/pirate'
require 'models/price_estimate'

Expand Down Expand Up @@ -194,6 +195,14 @@ def test_has_many_through_reflection
assert_kind_of ActiveRecord::Reflection::ThroughReflection, Subscriber.reflect_on_association(:books)
end

def test_collection_association?
assert Pirate.reflect_on_association(:birds).collection_association?
assert Pirate.reflect_on_association(:parrots).collection_association?

assert !Pirate.reflect_on_association(:ship).collection_association?
assert !Ship.reflect_on_association(:pirate).collection_association?
end

private
def assert_reflection(klass, association, options)
assert reflection = klass.reflect_on_association(association)
Expand Down

0 comments on commit f82adc7

Please sign in to comment.