maxenglander
maxenglander

Reputation: 4041

How can I check if one ActiveRecord class belongs to another

Given two subclasses of ActiveRecord::Base, how can I implement a function that checks to see if one belongs to the other?

def ClazzA < ActiveRecord::Base
  belongs_to :clazz_b
end

def ClazzB < ActiveRecord::Base has_many :clazz_a end

def belongs_to? a, b ... end

Thanks! Max

Upvotes: 4

Views: 1839

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

Try this:

def belongs_to? a, b
  b.reflect_on_all_associations(:belongs_to).
    any?{|bta| bta.association_class == a}
end

Note:

This question was unanswered when I started answering. After completing the answer I noticed the answer posted by @zeteic. I am letting the answer stand as this solution will work even for cases when the association name doesn't map to model name.

Upvotes: 2

zetetic
zetetic

Reputation: 47548

  def belongs_to?(a,b)
    sym = b.to_s.downcase.to_sym
    a.reflect_on_all_associations(:belongs_to).map(&:name).include?(sym)
  end

> belongs_to?(ClazzA,ClazzB) # true
> belongs_to?(ClazzB,ClazzA) # false

Upvotes: 5

Related Questions