Activerecord Rails 4.1枚举:enum.status=nil
我尝试了rails 4.1的新枚举功能,但遇到了一些问题 我的模型如下所示:Activerecord Rails 4.1枚举:enum.status=nil,activerecord,enums,ruby-on-rails-4.1,Activerecord,Enums,Ruby On Rails 4.1,我尝试了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} #... e
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">
现在看看这个:
[22] pry(main)> Report.all.sample.attributes['status']
Report Load (0.2ms) SELECT `reports`.* FROM `reports`
=> "3"
我不明白…我也有同样的问题。这是因为枚举字段在我的架构中被定义为字符串而不是整数。在您的情况下,
status
可能被定义为模式中的字符串
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
class CreateReport
您也可以继续在模式中使用字符串,但这意味着您必须使用哈希显式地映射属性和数据库值之间的关系。
像这样的东西
enum status: { started: 'START', active: 'ACT', fail: 'FAIL', success: 'SUCC'}
我有一个类似的问题:为什么我的枚举值总是被解析为nil@WillKoehler的回答起到了作用。我遵循了这个模式,但是我如何在视图中提供它呢。这就是我现在所拥有的:`
enum status: { started: 'START', active: 'ACT', fail: 'FAIL', success: 'SUCC'}