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

Babur Usenakunov picture Babur Usenakunov · Nov 26, 2011 · Viewed 9.6k times · Source

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

Answer

KARASZI Istv&#225;n picture KARASZI István · Nov 26, 2011

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 }