1

Rails 4.1 has enums available. I checked it out and it seemed to be working great in the rails console. When I try to persist data from a view to the database through my controller I get the following error

'Registration' is not a valid stream_type

Below is my class

class Stream < ActiveRecord::Base
  enum stream_type: { sales: 1, registration: 2, student: 3 }

  belongs_to :course_presentation

  has_many :subscriptions
  has_many :contacts, :through => :subscriptions

  validates :course_presentation_id, :stream_type, presence: true 
end

Below is the code i use to save

@stream = Stream.new(stream_params)

def stream_params
      params.require(:stream).permit(:stream_type, :course_presentation_id, :is_active, :created_by_user_id, :updated_by_user_id)
    end

below is the view code

<%= f.label :stream_type %><br>
    <%= f.collection_select :stream_type, StreamType.order(:name), :name, :name, include_blank: "<-- select -->" %>

Any ideas? I just can't get it working

Ryan-Neal Mes
  • 6,003
  • 7
  • 52
  • 77

1 Answers1

7

I figured this out, although not entirely happy with the answer. The dropdown storing the enum values were uppercase. e.g. "Registration". When it tried to save it can't find "Registration", but it can find "registration". Saving enums with the correct case works just fine.

Anyway, I would have hoped I could use integers corresponding to the hash key, but that doesn't seem to work.

Edited

Another way to solve this would be ...

params.require(:stream).permit(:stream_type, :course_presentation_id, :is_active, :created_by_user_id, :updated_by_user_id).tap do |w|
      w[:stream_type] = w[:stream_type].to_i if w[:stream_type]
end

And Another post I found

Alternative solution

Community
  • 1
  • 1
Ryan-Neal Mes
  • 6,003
  • 7
  • 52
  • 77
  • `Stream.new(stream_type: 1)` works, but `Stream.new(stream_type: '1')` doesn't work. Since params[:stream_type] will always be '1', it won't work. ActiveRecord should implicity convert it to an integer for this to work. – Abdulsattar Mohammed Mar 29 '14 at 08:21
  • I had the same problem with Rails 4.1. Solved it by change the value to integer before saving or updating the params. – GLindqvist Apr 28 '14 at 18:45
  • You can build a custom collection for select options to fix this. Rather than the usual [name, id], use something like [name.titleize, name]. The key is to assign the name as the value, not the ID like you would for any other database field. – nateware Jun 24 '14 at 20:19