以编程方式获取 Rails 4 中belongs_to关联的类



假设我有一些由一对多关系链接的类:

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)

最新更新