0

this is my tables looks like:

class Promo < ActiveRecord::Base {
             :id => :integer,
     :product_id => :integer,
     :promo_code => :string,
           :name => :string,
    :description => :text,
        :user_id => :string,
          :email => :string,
         :status => :integer,
       :category => :integer,
    :expire_date => :date,
     :user_limit => :integer,
     :created_at => :datetime,
     :updated_at => :datetime
}

ane here is my model:

class Promo < ActiveRecord::Base
  enum category: [ :discount, :rebate, :custom]
  enum status: [ :offered, :claimed, :redeemed ]
end

and my view:

<%= f.select :category, options_for_select(Promo.categories.map { |w| w }, @promo.category) %>

which will generate html like this:

<select name="promo[category]" id="promo_category">
    <option value="0">discount</option>
    <option value="1">rebate</option>
    <option value="2">custom</option>
</select>

But when I try to save it, it throw an error which says:

'0' is not a valid category

How to save enum to database? thanks

UPDATE

I have found the link before.

I change it my view like this:

<%= f.select :category, options_for_select(Promo.categories.keys.to_a.map { |w| [w.humanize, w] }, @promo.category) %>

but back to my root problems, its not working, it says that :

ActiveRecord::RecordNotSaved: Failed to save the record
from /home/krismp/.rvm/gems/ruby-2.1.5/gems/activerecord-4.2.3/lib/active_record/persistence.rb:142:in `save!'

why this is happen?

kmp4hj
  • 61
  • 6
  • Possible duplicate of [Saving enum from select in Rails 4.1](http://stackoverflow.com/questions/23686265/saving-enum-from-select-in-rails-4-1) – wiesion Nov 06 '15 at 07:13
  • @wiesion please see my updated question – kmp4hj Nov 06 '15 at 07:20
  • Your original question is a duplicate, and your edit makes this a new question. Also provide more content from the error stacktrace, just the "`Failed to save the record ... :in save!`" from https://github.com/rails/rails/blob/4-2-stable/activerecord/lib/active_record/persistence.rb#L142 is not helpful for debugging. – wiesion Nov 06 '15 at 07:29
  • the problem is there is no error throw in a rails server console, only rollback some query, I get above message using `pry` and `.save!` any idea. I really have follow your possible duplicate question link – kmp4hj Nov 06 '15 at 07:38

1 Answers1

0

The value submitted by this form snippet won’t validate because update is expecting the “string” key, and not the underlying numerical value of the table.

Instead, you can use following:

<%=  f.select :category, options_for_select(Promo.categories.map {|k,v| [k,k]}) %>

or

<%=  f.select :category, options_for_select(Promo.categories.map {|k,v| [k,k]}, @promo.category) %>
sadaf2605
  • 7,332
  • 8
  • 60
  • 103