假设我有一些通过一对多关系链接的类:
class A
field :name, type: String
has_many :b
class B
field :title, type: String
belongs_to :a
假设我有一个B的实例,我想检索他的belongs_to关系的类名(在我的示例中为“ A”,而不是链接到我的B对象的类型A的实例)。
a = A.new name: 'my A object'
b = B.new title: 'my B object', a: a
assert_equal b.get_relationships(:belongs_to), ['A'] #substitute "get_relationships" with something that actually exists :)
我该怎么办?
我在一个类似的主题上(使用反射)看了这个答案,但是我无法使它起作用。也许Rails 4发生了什么变化?
B.reflect_on_all_associations(:belongs_to).map(&:name)
或者
b.class.reflect_on_all_associations(:belongs_to).map(&:name)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句