Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.1 Enums: enum.status = nil

I tried the new enum Feature of rails 4.1 and have some troubles with it.

My model looks like this:

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

And if I try to use it in my view like this:

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

I'll see this in my browser

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

I tried to find out what status actually is using 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

And now look at this:

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

I don't get it...

like image 308
Ich Avatar asked Apr 10 '14 08:04

Ich


2 Answers

I had the same problem. It was caused because the enum field was defined as a string in my schema instead of an integer. In your case, status is probably defined as a string in your schema.

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
like image 60
Will Koehler Avatar answered Nov 07 '22 18:11

Will Koehler


Also you can continue to use string in your schema, but it means that you have to explicitly map relation between attribute and database value using hash. Something like this;

enum status: { started: 'START', active: 'ACT', fail: 'FAIL', success: 'SUCC'}
like image 34
kakoni Avatar answered Nov 07 '22 20:11

kakoni