繁体   English   中英

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

[英]How do I handle selected values in a nested association in 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

在我的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 %>

所以,这向我grade_types了enum值中的grade_types ,就像我期望的那样。

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

我怎么做?

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

我不太确定对嵌套属性做同样的事情,但肯定看起来像是我喜欢学习的东西

从成绩对象g.object获取grade_type,并通过选中的方式将其传递给输入字段:

<%= f.input_field :grade_type, collection: Grade.grade_types.keys, selected: g.object.grade_type, include_blank: false, class: 'col-lg-8 form-control' %>

enum_help gem允许您这样做:

<%= f.input :grade_type %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM