rails, simple_form, how to update the radio buttons with the selected option after saving?
Asked Answered
B

1

6

I'm pretty new to rails and this is also my first post, but I'm trying to create a simple_form on a view page which should be a Settings page for some User and I've already searched for 2 days now for an answer and I can't find it anywhere.

<%= f.input :gender, label: 'What is your gender?', collection: [ ['M', 'Male' ], ['F', 'Female'] ], as: :radio_buttons, label_method: :last, value_method: :first, checked: 'M', item_wrapper_class: 'inline'%>

This is my input label and the only option so far is to set :checked => 'M', so that after saving the users settings the radio button will be selected (but this won't be correct if I'm selecting the 'Female' gender, because after saving the Settings page, the 'Male' radio button will be selected by default).

So is there any way to use radio buttons in simple form (or even a dropdown list) so that after saving the page the gender will remain selected?

Bratton answered 30/8, 2012 at 14:3 Comment(0)
I
18

Try using the user gender attribute instead of "M" fo checked:

<%= f.input :gender, label: 'What is your gender?', collection: [ ['M', 'Male' ], ['F', 'Female'] ], as: :radio_buttons, label_method: :last, value_method: :first, checked: @user.gender, item_wrapper_class: 'inline'%>
Inhibitor answered 30/8, 2012 at 14:14 Comment(3)
Thanks a lot for the quick response, that should solve my problemBratton
This answered my question as well. But how do I prevent the form from defaulting to the checked default in the edit view? Or, put another way, how to we have this checked option in only 'new' and not 'edit'?Alchemize
cpursely one way to do this is (defaulting to Male in 'new' and nothing in 'edit'): ..., checked: params[:action] == 'new' ? 'M' : nilPhotoconductivity

© 2022 - 2024 — McMap. All rights reserved.