简体   繁体   English

两种模型之间的Rails关系

[英]Rails Relationship Between Two Models

Is there a way to determine the relationship method Rails creates between two models dynamically? 有没有办法确定Rails在两个模型之间动态创建的关系方法?

For example: 例如:

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

Looked over Rails API but nothing screamed at me that it could do this. 查看了Rails API,但没有人向我尖叫,它可以做到这一点。

Essentially the inverse of these methods: http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#method-i-reflect_on_association 这些方法实质上是相反的: http : //api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#method-i-reflect_on_association

Are you looking for something like this? 您是否正在寻找这样的东西?

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM