Ich*_*Ich 8 enums activerecord 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}
#...
end
Run Code Online (Sandbox Code Playgroud)
如果我尝试在我看来这样使用它:
.item{class: @report.status, data: {id: @report.id}}
Run Code Online (Sandbox Code Playgroud)
我会在浏览器中看到这个
<div class="item" data-id="25">
Run Code Online (Sandbox Code Playgroud)
我试图找出status实际使用的内容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
Run Code Online (Sandbox Code Playgroud)
现在看看这个:
[22] pry(main)> Report.all.sample.attributes['status']
Report Load (0.2ms) SELECT `reports`.* FROM `reports`
=> "3"
Run Code Online (Sandbox Code Playgroud)
我不明白......
Wil*_*ler 16
我有同样的问题.之所以这是因为枚举字段在我的模式中定义为字符串而不是整数.在您的情况下,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
Run Code Online (Sandbox Code Playgroud)