两种模型之间的Rails关系

时间:2013-04-24 16:55:19

标签: ruby-on-rails models relationships

有没有办法确定Rails在两个模型之间动态创建的关系方法?

例如:

unknown_method_i_wish_existed(class_name_1, class_name_2)
  # awesome logic
  # returns the relationship method name going from class_name_1 to class_name_2
end

查看了Rails API,但没有任何事情让我尖叫它可以做到这一点。

基本上是这些方法的反面:http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#method-i-reflect_on_association

1 个答案:

答案 0 :(得分:1)

你在找这样的东西吗?

def reflection_names_between(from, to)
  from.reflections.select { |name, refl| refl.klass == to }.values.map(&:macro)
end

# For a Car that has one :owner and many :passengers
reflection_names_between(Car, User) # => [:belongs_to, :has_many]