Tuesday, October 4, 2016

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

Leave a Comment

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?

3 Answers

Answers 1

simple_form has a nifty option to preselect a value. You could either use the :selected option for this as such:

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

I'm not really sure of doing the same for nested attributes though, but sure seems like something I'd love to learn

Answers 2

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

Answers 3

The enum_help gem lets you do this:

<%= f.input :grade_type %> 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment