Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle selected values in a nested association in simple_form?

I have a Profile model, that accepts_nested_attributes_for :grades.

My Grade model looks like this:

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

In my profiles/_form.html.erb, I have the following:

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

So, that shows me the grade_types from the enum values like I would expect.

But what I want to happen is, when I am editing a record, and it shows the grades, it should have the grade_type pre-selected.

How do I do that?

like image 230
marcamillion Avatar asked Sep 25 '16 15:09

marcamillion


1 Answers

Get the grade_type from the grade object g.object and pass it to the input field via 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' %>
like image 101
Jawad Khawaja Avatar answered Oct 15 '22 13:10

Jawad Khawaja