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

时间:2016-09-25 15:20:17

标签: ruby-on-rails simple-form nested-forms nested-attributes

我有一个max{t in 0..T} production[t]模型,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_type。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

public class RiddleViewModel { [Required] public string Name { get; set; } [MaxLength(200)] [DataType(DataType.MultilineText)] public string Description { get; set; } // Question properties [DataType(DataType.MultilineText)] public string FirstQuestionBody { get; set; } public string FirstQuestionAnswer { get; set; } } 有一个很好的选择来预选一个值。您可以使用simple_form选项:

:selected

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

答案 1 :(得分:0)

从成绩对象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' %>

答案 2 :(得分:0)

enum_help gem允许您这样做:

<%= f.input :grade_type %>
相关问题