如何在simple_form中处理嵌套关联中的选定值?

mar*_*ion 7 ruby-on-rails nested-forms nested-attributes simple-form

我有一个Profile模特,那个accepts_nested_attributes_for :grades.

我的Grade模型看起来像这样:

# == Schema Information
#
# Table name: grades
#
#  id         :integer          not null, primary key
#  subject    :string
#  result     :string
#  grade_type :integer
#  profile_id :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null

class Grade < ActiveRecord::Base
  belongs_to :profile

  enum grade_type: { csec: 0, cape: 1, sat: 2, g7: 3, g8: 4, g9: 5, g10: 6, g11: 7, g12: 8, g13: 9 }
end
Run Code Online (Sandbox Code Playgroud)

在我profiles/_form.html.erb,我有以下内容:

<%= simple_form_for @profile, html: { class: "form-horizontal" } do |f| %>
  <%= f.simple_fields_for :grades, html: { class: "form-inline" } do |g| %>
    <%= g.input_field :grade_type, collection: Grade.grade_types.keys, include_blank: false, class: 'col-lg-8 form-control' %>
  <% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

所以,这向我展示了grade_types我所期望的枚举值.

但我想要发生的是,当我编辑一个记录时,它显示了成绩,它应该预先选择grade_type.

我怎么做?

ore*_*uwa 0

simple_form有一个漂亮的选项来预先选择一个值。您可以使用:selected以下选项:

<%= f.input_field :grade_type, collection: Grade.grade_types.keys, include_blank: false, class: 'col-lg-8 form-control', selected: @grade[:grade_type] %>
Run Code Online (Sandbox Code Playgroud)

虽然我不太确定是否对嵌套属性执行相同的操作,但确实似乎是我很想学习的东西