如何在 Rails 6 中使用变量作为列名

How use varaible as column name in Rails 6

我会缩短这段代码。

def foo type, user
  if type == "foo"
    user.foo
  elsif type == "bar"
    user.bar
  end
end

user 是 ActiveRecord 对象

type 是字符串“foo”或“bar”

如果我有更多 types,那么我需要赚更多 elsif。可以使用 type 变量作为列名来缩短它(不使用模型方法或任何其他附加代码)吗?类似于:

user.{type} # ???

您可以使用 public_send 来实现:

user.public_send(type)