使用字符串作为 Class 关联名称 Rails

Use string as Class Association Name Rails

我有一个方法,returns 协会的名称作为 string.This 是其代码:

def get_assoc_name
  Assoc.find(1).assoc_name
end

## Returns "foo"

另一个模型 class ("Bar") has_one "Foo" (:foo)。我正在尝试使用 "get_assoc_name" 的结果来表明我想像这样访问关联:

def get_bar_foo
  Bar.find(1)."#{get_assoc_name}"
end

## Should instantiate Bar.foo

以上是我多次失败的尝试之一。我知道您可以使用 "constantize" 从字符串中发起一个新的 class,但是如何使用字符串调用关联?

使用方法如下:

def get_bar_foo
  Bar.find(1).public_send get_assoc_name
end

当您将 method 命名为 SymbolString 时,您可以使用方法 public_send if the method is public method, or send 当方法是 私有 方法时。