加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:29:57 所属栏目:百科 来源:网络整理
导读:我尝试了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
我尝试了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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读