web-dev-qa-db-ja.com

モデルに関連付けずにsimple_formを使用してチェックボックスを追加しますか?

モデルと関連付けずにsimple_formでチェックボックスを追加するにはどうすればよいですか?いくつかのjavascriptイベントを処理するチェックボックスを作成したいのですが、知りませんか?おそらくドキュメントに何かが欠けているのでしょうか?次のようなものを使用したくない:

= simple_form_for(resource, as: resource_name, url: session_url(resource_name), wrapper: :inline) do |f|
  .inputs
    = f.input :email, required: false, autofocus: true
    = f.input :password, required: false
    = f.input :remember_me, as: :boolean if devise_mapping.rememberable?
    = my_checkbox, 'some text'
25
Mikhail Grishko

モデルにカスタム属性を追加できます。

class Resource < ActiveRecord::Base
  attr_accessor :custom_field
end

次に、このフィールドをブロックとして使用します。

= f.input :custom_field, :label => false do 
  = check_box_tag :some_name

ドキュメントで「Wrapping Rails Form Helpers」を見つけてください https://github.com/plataformatec/simple_form

36
Gacha

使用できます

f.input :field_name, as: :boolean
33
huoxito

Huoxitoによって提案されたコマンドは機能しません(少なくともRails 4)では機能しません。私が知る限り、エラーはRails :custom_fieldのデフォルト値を上げますが、このフィールドが存在しないため、このルックアップは失敗し、例外がスローされます。

ただし、:input_htmlパラメータを使用してフィールドのデフォルト値を指定すると機能します。このような:

= f.input :custom_field, :as => :boolean, :input_html => { :checked => "checked" }
15
m4r73n

この質問はグーグルで最初に出され、適切な答えはありません。

Simple Form 3.1.0.rc1以降、Wikiで説明されている適切な方法があります。 https://github.com/plataformatec/simple_form/wiki/Create-a-fake-input-that-does -NOT-read-attributes

app/inputs/fake_input.rb

class FakeInput < SimpleForm::Inputs::StringInput
  # This method only create a basic input without reading any value from object
  def input(wrapper_options = nil)
    merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
    template.text_field_tag(attribute_name, nil, merged_input_options)
  end
end

その後、<%= f.input :thing, as: :fake %>

この特定の質問については、メソッドの2行目を次のように変更する必要があります。

template.check_box_tag(attribute_name, nil, merged_input_options)

3.1.0.rc1より前のバージョンの場合、admgcは欠落しているメソッドmerge_wrapper_options

https://stackoverflow.com/a/26331237/2055246

3
eXa

これをapp/inputs/arbitrary_boolean_input.rbに追加します:

class ArbitraryBooleanInput < SimpleForm::Inputs::BooleanInput
  def input(wrapper_options = nil)
    tag_name = "#{@builder.object_name}[#{attribute_name}]"
    template.check_box_tag(tag_name, options['value'] || 1, options['checked'], options)
  end
end

次のようにビューで使用します:

= simple_form_for(@some_object, remote: true, method: :put) do |f|
  = f.simple_fields_for @some_object.some_nested_object do |nested_f|
    = nested_f.input :some_param, as: :arbitrary_boolean

つまり、上記の実装はネストされたフィールドを正しくサポートします。私が見た他の解決策はありません。

注:この例はHAMLです。

2
Benjamin Dobell