4

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

maxenglander
  • 3,991
  • 4
  • 30
  • 40

2 Answers2

5
  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
zetetic
  • 47,184
  • 10
  • 111
  • 119
  • You might want to define this in the model as a class method to make it easier to read, a la: Clazza.belongs_to?(ClazzB) – zetetic Sep 20 '11 at 02:24
  • in my controller, I had to change the second line to: sym = b.class.name.to_s.downcase.to_sym – alalani Jul 06 '13 at 21:29
2

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.

Harish Shetty
  • 64,083
  • 21
  • 152
  • 198