2017-08-15 121 views
0

我打算在simple_form中设置radio_buttons的默认值。这是我的代码:如何设置简单形式的radio_buttons的默认值

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

我添加了一个选项checked: ‘custom’。当创建一个新库时,custom将被默认选中。

但是,如果用户已经选择了library_type,则会导致错误。当用户编辑库时,即使用户选择了standard,也会选择custom

任何人都知道如何解决这个问题?谢谢。

回答

1

我会将这个逻辑移动到控制器。 在new操作中,您必须将library_type字段设置为custom,并且它会为您执行此操作。 喜欢的东西

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 

所以,将设立library_typecustom的新实例,不会覆盖它已经创造了记录。

+0

谢谢,这就是我想要的答案。 – Stephen