Babur Ussenakunov
Babur Ussenakunov

Reputation: 1995

Is there any way to check that has_many association exists in Rails 3.1?

For example there are some models

class Model_1 < ActiveRecord::Base
   has_many :images, :as => :imageable
end

class Model_2 < ActiveRecord::Base
   # doesn't have has_many association
end
...
class Image < ActiveRecord::Base
    belongs_to :imageable, :polymorphic => true
end

How can I check that model has has_many association? Something like this

class ActiveRecord::Base
    def self.has_many_association_exists?(:association)
        ...
    end
end

And it can be used so

Model_1.has_many_association_exists?(:images) # true
Model_2.has_many_association_exists?(:images) # false

Thanks in advance

Upvotes: 18

Views: 13203

Answers (4)

Jignesh Gohel
Jignesh Gohel

Reputation: 6552

I found the following to be the simple way to achieve the desired result:

ModelName.method_defined?(:method_name)

Example:

Model_1.method_defined?(:images) # true
Model_2.method_defined?(:images) # false

Reference: https://stackoverflow.com/a/18066069/936494

Upvotes: 4

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

What about reflect_on_association?

Model_1.reflect_on_association(:images)

Or reflect_on_all_associations:

associations = Model_1.reflect_on_all_associations(:has_many)
associations.any? { |a| a.name == :images }

Upvotes: 24

ktec
ktec

Reputation: 2473

You could probably use respond_to?

class ActiveRecord::Base
    def self.has_many_association_exists?(related)
        self.class.associations.respond_to?(related)
    end
end

Upvotes: 1

Spyros
Spyros

Reputation: 48616

You could just have a method that tries to access a Model_1 object images inside an exception block like (roughly) :

begin
  model1_obj.images
rescue
  puts 'No association between model_1 and images'
end

Inside rescue, you can just return false if you like.

Upvotes: 0

Related Questions