rails + simpleform:selected未设置为enum的值

时间:2016-01-25 15:24:58

标签: ruby-on-rails ruby-on-rails-4 enums simple-form

我的用户模型的枚举定义。

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

在simple_form中我有:

<%= 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 %>

然而,似乎虽然用户的program_of_study'program_of_study_science'(通过检查rails控制台),但当我呈现表单时,显示的select元素仍然具有'program_of_study_unknown' as显示的那个。没有选择正确的。

2 个答案:

答案 0 :(得分:0)

我没有使用枚举,而是使用了键,它似乎有用,你试过了吗?

collection: User.program_of_studies.keys

我没有指定selected选项。我的代码如下所示:

input :status, as: :select, collection: Venue.statuses.keys, include_blank: false

答案 1 :(得分:0)

我的解决方案到底

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