2017-08-15 32 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