【问题标题】:Rails API - Casting string parameters to enum valuesRails API - 将字符串参数转换为枚举值
【发布时间】:2021-08-19 20:02:34
【问题描述】:

在 Ruby on Rails 应用程序中,假设有一个带有 enum 字段的模型,例如:

class Car < ActiveRecord::Base
  enum color: {
    blue: 0,
    green: 1,
    red: 2
  }
end

有一个 API 端点用于创建我的模型的新实例。

为params[:color] 发送的值与enum 键不匹配。 (例如,“深海蓝”之类的东西作为参数值发送)。

我知道我可以将我的 enum 更改为:

class Car < ActiveRecord::Base
  enum color: {
    'Deep Ocean Blue' => 0,
    # ... etc.
  }
end

但这使得 Rails 为 enum 生成的方法很奇怪且难以使用...

my_car.blue?
my_car.send('Deep Ocean Blue?') # not even sure this works but you get the idea

我的问题是,处理这种情况的最佳(“Railsiest”)方法是什么?

我应该创建参数和枚举键的映射,并在 before_validation 钩子中转换正确的枚举值,还是有更好的处理方法?

谢谢!

【问题讨论】:

  • 您可以使用deep_blue_ocean,如果您需要显示它,那么to_s.humanize 应该解决这个问题,并且可以由underscore 处理转换回来。如果您的代码中已经充斥着这些调用,或者您只有 1 个蓝色,您甚至可以使用 alias_method :blue?, :deep_blue_ocean?。

标签: ruby-on-rails ruby api ruby-on-rails-5


【解决方案1】:

如果您有固定颜色选项,您可以尝试使用underscore 方法

2.6.5 :007 > "Deep Ocean Blue".parameterize.underscore
=> "deep_ocean_blue" 

您可以将枚举保留为

class Car < ActiveRecord::Base
  enum color: {
    'deep_ocean_blue' => 0,
    'golden_rose' => 1,
    # ... etc.
  }
end

在创建对象时将参数颜色转换为underscore

Car.create(color: params[:color].parameterize.underscore, # other parameters ..)

【讨论】:

    猜你喜欢
    • 2014-09-27
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    相关资源
    最近更新 更多