Given tw开发者_开发知识库o 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
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
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.
精彩评论