如何以简单形式设置默认值 radio_buttons

How to set a default value of radio_buttons in simple-form

我将在 simple_form 中设置 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 将默认为 selected。

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

有人知道怎么解决吗?谢谢。

我会将此逻辑移至控制器。 在 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,并且不会为已创建的记录覆盖它。