2013-04-24 118 views
2

有沒有一種方法可以確定Rails在兩個模型之間動態創建的關係方法?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

您正在尋找這樣的事情?

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]