Search code examples
ruby-on-railsruby-on-rails-4enumssimple-form

rails + simpleform: selected does not set to be enum's value


I have a enum definition for my User model.

class User < ActiveRecord::Base
  enum program_of_study: [
    :program_of_study_unknown, :program_of_study_cs, :program_of_study_ceg,
    :program_of_study_is, :program_of_study_science,
    :program_of_study_engineering, :program_of_study_fass,
    :program_of_study_business, :program_of_study_others
  ]
end

And in simple_form I have:

<%= simple_form_for(locals[:user], wrapper: :horizontal_form, html: {class: 'form-horizontal'},
                    url: {action: (locals[:is_new] ? 'create' : 'update')}) do |f| %>
    <%= f.error_notification %>
    <%= f.input :program_of_study, collection: User.program_of_studies, include_blank: false, selected: locals[:user].program_of_study %>
    <%= f.button :submit, class: 'btn-success' %>
<% end %>

However, it seems that although the program_of_study of a user is 'program_of_study_science'(by checking in rails console), when I render the form, the shown select element still has 'program_of_study_unknown' as the displayed one. The correct one was not selected.


Solution

  • My solution in the end

    <%= f.input :program_of_study, collection: User.program_of_studies, include_blank: false, selected: User.program_of_studies[locals[:user].program_of_study] %>