Ich
Ich

Reputation: 1378

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...

Upvotes: 10

Views: 5347

Answers (2)

kakoni
kakoni

Reputation: 5130

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'}

Upvotes: 2

Will Koehler
Will Koehler

Reputation: 1766

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

Upvotes: 18

Related Questions