From 67c390ae4cfed8dc7923fcab0980302af1f8aeea Mon Sep 17 00:00:00 2001 From: Vijay Aravamudhan Date: Sun, 5 Apr 2009 14:37:07 -0500 Subject: [PATCH] Added utility method that can be used while serializing (for eg in to_xml) to denote whether any associated objects exist at that time. --- activerecord/lib/active_record/reflection.rb | 8 +++++++ activerecord/test/cases/reflection_test.rb | 28 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index 2d4c1d5..c4c4278 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -140,6 +140,14 @@ module ActiveRecord # Holds all the meta-data about an association as it was specified in the Active Record class. class AssociationReflection < MacroReflection #:nodoc: + def initialize(macro, name, options, active_record) + super(macro, name, options, active_record) + if active_record && name + active_record.send(:define_method, "has_#{name}?") { !self.send(name).blank? } + active_record.send(:alias_method, "has_#{name}", "has_#{name}?") + end + end + # Returns the target association's class: # # class Author < ActiveRecord::Base diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index db64bbb..5458776 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -184,6 +184,34 @@ class ReflectionTest < ActiveRecord::TestCase assert_kind_of ActiveRecord::Reflection::ThroughReflection, Subscriber.reflect_on_association(:books) end + def test_belongs_to_association_defines_has_associated_object_method + Company.belongs_to :foo + company = Company.new + assert company.respond_to?(:has_foo?) + assert company.respond_to?(:has_foo) + end + + def test_has_one_association_defines_has_associated_object_method + Company.has_one :foo + company = Company.new + assert company.respond_to?(:has_foo?) + assert company.respond_to?(:has_foo) + end + + def test_has_many_association_defines_has_associated_object_method + Company.has_many :foos + company = Company.new + assert company.respond_to?(:has_foos?) + assert company.respond_to?(:has_foos) + end + + def test_has_and_belongs_to_many_association_defines_has_associated_object_method + Company.has_and_belongs_to_many :foos + company = Company.new + assert company.respond_to?(:has_foos?) + assert company.respond_to?(:has_foos) + end + private def assert_reflection(klass, association, options) assert reflection = klass.reflect_on_association(association) -- 1.6.0.5