【问题标题】:How do I handle selected values in a nested association in simple_form?如何处理 simple_form 中嵌套关联中的选定值?
【发布时间】:2016-09-25 15:20:17
【问题描述】:

我有一个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,就像我期望的那样。

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

我该怎么做?

【问题讨论】:

  • 您是否将控制器中的grade_types 参数列入白名单? require(:profile).permit(grades_attributes: [:grade_type])
  • @max 是的。那不是问题。问题在于检测已选择的内容并对其进行识别。
  • 嗯,试试collection: User.statuses.map {|k,v| [k, k] } - SimpleForm 将ActionView::Helpers::FormOptionsHelper 委派下来,将g.object.grade_type 链接到选项时可能会遇到问题。

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


【解决方案1】:

从成绩对象g.object中获取grade_type,并通过selected传递给输入字段:

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

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

    虽然我不确定是否对嵌套属性做同样的事情,但我确实很想学习

    【讨论】:

    • 是的,我知道:selected。但我真正苦苦挣扎的是嵌套属性部分,以及所述嵌套属性的枚举值。
    【解决方案3】:

    enum_help gem 让您可以这样做:

    <%= f.input :grade_type %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 2019-01-16
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      相关资源
      最近更新 更多