【问题标题】:ActiveRecord enum error: "is not a valid value"ActiveRecord 枚举错误:“不是有效值”
【发布时间】:2017-01-09 19:02:07
【问题描述】:

我有一个带有枚举的模型:

  enum pending_users: {
    pending_users_disabled: 0,
    pending_users_enabled: 1
  }

下面是 schema.rb 中描述的字段:

t.integer  "pending_users",             limit: 4,     default: 0, null: false

当我尝试使用以下参数通过控制器更新它时:

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "group"=>{"pending_users"=>"1"}, "commit"=>"Update Group", "id"=>"33"}

我看到以下错误:

ArgumentError - '1' is not a valid pending_users:
  activerecord (4.2.7.1) lib/active_record/enum.rb:104:in `block (3 levels) in enum'
  activerecord (4.2.7.1) lib/active_record/attribute_assignment.rb:54:in `_assign_attribute'
  activerecord (4.2.7.1) lib/active_record/attribute_assignment.rb:41:in `block in assign_attributes'
  actionpack (4.2.7.1) lib/action_controller/metal/strong_parameters.rb:185:in `each_pair'
  activerecord (4.2.7.1) lib/active_record/attribute_assignment.rb:35:in `assign_attributes'
  activerecord (4.2.7.1) lib/active_record/persistence.rb:251:in `block in update'
  activerecord (4.2.7.1) lib/active_record/transactions.rb:351:in `block in with_transaction_returning_status'
  activerecord (4.2.7.1) lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `block in transaction'
  activerecord (4.2.7.1) lib/active_record/connection_adapters/abstract/transaction.rb:184:in `within_new_transaction'
  activerecord (4.2.7.1) lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `transaction'
  activerecord (4.2.7.1) lib/active_record/transactions.rb:220:in `transaction'
  activerecord (4.2.7.1) lib/active_record/transactions.rb:348:in `with_transaction_returning_status'
  activerecord (4.2.7.1) lib/active_record/persistence.rb:250:in `update'
  app/controllers/groups_controller.rb:53:in `update'

在我看来,1 是枚举的有效值。什么会导致这种行为?

【问题讨论】:

  • 你真的应该使用enum pending_users: %w(enabled disabled)pending_users_ 前缀是多余的。
  • @meagar 我没有在这里包含整个模型。事实上,我的模型中还有其他启用/禁用的枚举,不幸的是,rails 4 中无法包含几个具有相同值的不同枚举

标签: ruby-on-rails forms activerecord enums


【解决方案1】:

您应该为枚举分配一个字符串(键)。所以1 应该是"pending_users_enabled"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多