Blankman
Blankman

Reputation: 267030

Using enum in a model, when saving it doesn't like the integer value

Using rails 4.1.1

My model has an enum like:

class Article < ActiveRecord::Base
  enum article_status: { published: 1, draft :2 }

Now in my new.html.erb I have:

<%= form.select :article_status, options_for_select(Article.article_statuses) %>

When going to save the model I get this error:

'1' is not a valid article_status

I was thinking it would be able to handle this during an update.

What am I doing wrong?

Upvotes: 1

Views: 1243

Answers (1)

Gene
Gene

Reputation: 46960

The update_attributes or new call in your controllers will expect the stringified version of the enum symbol, not the integer. So you need something like:

options_for_select(Article.article_statuses.
  collect{|item, val| [item.humanize, item]}, selected: @article.status)

There is a full example in this article.

Upvotes: 5

Related Questions