Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 558
Babur Ussenakunov Avatar asked Nov 26 '11 20:11

Babur Ussenakunov


People also ask

How many types of associations are there in Rails?

Rails supports six types of associations: belongs_to.

What is Active Record :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What does Inverse_of do in Rails?

The :inverse_of option basically gives us two-way memory bindings when one of the associations is a :belongs_to . A memory optimization isn't the only thing that :inverse_of gets you.


2 Answers

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 }
like image 155
KARASZI István Avatar answered Oct 14 '22 11:10

KARASZI István


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

like image 38
Jignesh Gohel Avatar answered Oct 14 '22 09:10

Jignesh Gohel