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



我想让这段代码更短一些。

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

user是ActiveRecord对象

type是字符串"或";bar"

如果我有更多的types,那么我需要制造更多的elsif。有可能使它更短(不使用模型方法或任何其他额外的代码)使用type变量作为列名?比如:

user.{type} # ???

您可以使用public_send来实现这一点:

user.public_send(type)

最新更新