2

有没有办法动态确定 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

4

1 回答 1

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]
于 2013-05-08T08:36:57.830 回答