Reputation: 3992
I am going to set the default value for radio_buttons
in simple_form
. This is my code:
<%= f.input :library_type, as: :radio_buttons, collection: Library.library_types.collect { |k,_| [k.capitalize, k]} , checked: 'custom’%>
class Library < ActiveRecord::Base
enum library_type: [:standard, :custom]
...
end
2.2.3 :002 > Library.library_types.collect { |k,_| [k.capitalize, k]}
=> [["Standard", "standard"], ["Custom", "custom"]]
I added a option checked: ‘custom’
. when creating a new library, the custom
would be default selected.
However, this will cause an error that when a user already choose a library_type
. When a user edit a library, it will select the custom
as well, even if the user selected the standard
.
Anyone know how to solve this? Thanks.
Upvotes: 0
Views: 630
Reputation: 4814
I would move this logic to the controller.
In new
action you have to set the library_type
field to custom
, and it will do it for you.
Something like
class LibrariesController < ApplicationController
def new
@library = Library.new(library_type: 'custom')
render 'edit'
end
def create
...
end
def edit
#find @library here
render 'edit'
end
def update
...
end
end
So, it will set up library_type
to custom
for new instances and will not overwrite it for already created records.
Upvotes: 1