2013-04-24 3 views
2

레일즈가 두 모델 사이에서 동적으로 만드는 관계 방법을 결정하는 방법이 있습니까? 예를 들어레일 관계 두 모델 사이의 관계

는 :

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 

레일 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]