Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 名称为整数的枚举_Ruby On Rails_Enums - Fatal编程技术网

Ruby on rails 名称为整数的枚举

Ruby on rails 名称为整数的枚举,ruby-on-rails,enums,Ruby On Rails,Enums,在我的用户模型中,我试图用包含数字的名称声明一个枚举,如下所示: class User < ApplicationRecord enum age_group: [ '18_to_22', '23_to_27', '28_to_32', '33_to_37', '38_to_42' ] end 除了使用其他名称和从前端处理问题外,还有其他解决方法吗?您正在尝试使用enum提供的方便方法,但不必使用这些方法。您可以使用更传统的,其中查询: User

在我的用户模型中,我试图用包含数字的名称声明一个枚举,如下所示:

class User < ApplicationRecord
enum age_group: [
    '18_to_22',
    '23_to_27',
    '28_to_32',
    '33_to_37',
    '38_to_42'
  ]
end

除了使用其他名称和从前端处理问题外,还有其他解决方法吗?

您正在尝试使用
enum
提供的方便方法,但不必使用这些方法。您可以使用更传统的
,其中
查询:

User.where(age_group: '18_to_22')
如果您喜欢使用方便的方法,那么您仍然可以使用
send
,但我认为这并不像使用
where
那样清楚:

User.send('18_to_22')

enum
在模型中为给定值创建作用域。和作用域名称不能以整数开头。 所以我能想到的唯一解决办法是:

enum age_group: [
  eighteen_to_twenty: '18_to_22',
  ...
  ...
]


你可以像
User.earth_to_two
User.\u 18_to_22

一样使用它。是的,我同意两者都可以,但第一个太长了,不能使用,例如“三十八到四十二”太长了。第二个选项更好,但很难看:)使用send-here不是很清楚,我想我会坚持使用老式的where,谢谢
enum age_group: [
  eighteen_to_twenty: '18_to_22',
  ...
  ...
]
enum age_group: [
  _18_to_20: '18_to_22',
  ...
  ...
]