使用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'
您可以向模型添加自定义属性:
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
你可以用
f.input :field_name, as: :boolean
huoxito提出的命令不起作用(至少在Rails 4中没有)。 据我所知,错误是由Rails尝试查找:custom_field
的默认值引起的,但由于此字段不存在,此查找失败并引发exception。
但是,如果使用:input_html
参数为字段指定默认值,则它可以工作,例如:
= f.input :custom_field, :as => :boolean, :input_html => { :checked => "checked" }
这个问题首先在谷歌上没有适当的答案。
从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 %>
对于此特定问题,您必须将方法的第二行更改为:
template.check_box_tag(attribute_name, nil, merged_input_options)
对于3.1.0.rc1之前的版本,admgc提供了一个解决方案,即添加缺少的方法merge_wrapper_options
:
将其添加到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。