【问题标题】:How use varaible as column name in Rails 6如何在 Rails 6 中使用变量作为列名
【发布时间】:2021-11-19 03:15:06
【问题描述】:

我会缩短这段代码。

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} # ???

【问题讨论】:

  • 类型总是等于方法名?如果是这样,您可以使用user.public_send(type)
  • 是的,这正是我的意思!谢谢

标签: ruby-on-rails ruby activerecord


【解决方案1】:

您可以使用public_send 来实现:

user.public_send(type)

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 2019-02-24
    • 2013-11-29
    • 1970-01-01
    • 2023-03-30
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多