How to handle selected values ​​in a nested association in simple_form?

I have a Profile model that accepts_nested_attributes_for :grades .

My Grade model is as follows:

 # == 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, this shows me grade_types from the enum values ​​as I expected.

But I want this to happen when I edit a record and it shows the ratings, it must have a predefined connection_type.

How to do it?

+7
ruby-on-rails nested-forms nested-attributes simple-form
source share
3 answers

simple_form has a great option for pre-selecting a value. You can 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 sure if I am doing the same for nested attributes, but of course it looks like what I would like to know.

0
source share

Get class_type from the class object g.object and pass it to the input field using the 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' %> 
0
source share

enum_help gem allows you to do this:

 <%= f.input :grade_type %> 
0
source share

All Articles