activerecord – Rails 4.1枚举:enum.status = nil

前端之家收集整理的这篇文章主要介绍了activerecord – Rails 4.1枚举:enum.status = nil前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试了rails 4.1的新枚举功能并且遇到了一些麻烦.

我的模型看起来像这样:

class Report < ActiveRecord::Base
  after_save :notify_clients
  before_update :update_progress
  before_create do
    self.status ||= 'started'
  end

  enum status: %w{started active fail success}

  #...
end

如果我尝试在我看来这样使用它:

.item{class: @report.status,data: {id: @report.id}}

我会在浏览器中看到这个

<div class="item" data-id="25">

我试图找出使用rails console的实际状态:

[11] pry(main)> Report.all.sample.status
    Report Load (0.3ms)  SELECT `reports`.* FROM `reports`
  => nil
  [12] pry(main)> Report.all.sample.status
    Report Load (0.2ms)  SELECT `reports`.* FROM `reports`
  => nil
  [13] pry(main)> Report.all.sample.status
    Report Load (0.3ms)  SELECT `reports`.* FROM `reports`
  => nil
  [14] pry(main)> Report.all.sample.status
    Report Load (0.2ms)  SELECT `reports`.* FROM `reports`
  => nil

现在看看这个:

[22] pry(main)> Report.all.sample.attributes['status']
    Report Load (0.2ms)  SELECT `reports`.* FROM `reports`
  => "3"

我不明白……

解决方法

我有同样的问题.之所以这是因为枚举字段在我的模式中定义为字符串而不是整数.在您的情况下,状态可能被定义为架构中的字符串.
class CreateReport < ActiveRecord::Migration
  def change
    create_table :reports do |t|
      ...
      t.integer :status     # if this is t.string you get the symptoms described above!
      ...
    end
  end
end

猜你在找的Ruby相关文章