开发者

How can I check if one ActiveRecord class belongs to another

开发者 https://www.devze.com 2023-04-05 20:07 出处:网络
Given tw开发者_开发知识库o subclasses of ActiveRecord::Base, how can I implement a function that checks to see if one belongs to the other?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号