添加带有simple_form且未与模型关联的复选框?

问题描述 投票:28回答:6

如何在不与模型关联的情况下添加带有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'
ruby-on-rails haml simple-form
6个回答
36
投票

您可以向模型添加自定义属性:

class Resource < ActiveRecord::Base
  attr_accessor :custom_field
end

然后将该字段用作块:

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

尝试在其文档https://github.com/plataformatec/simple_form中找到“包装Rails表单帮助程序”


35
投票

您可以使用

f.input :field_name, as: :boolean

16
投票

huoxito提出的命令不起作用(至少在Rails 4中不起作用)。据我所知,该错误是由Rails尝试查找:custom_field的默认值引起的,但是由于此字段不存在,因此该查找失败并引发异常。

但是,如果您使用:input_html参数为字段指定默认值,例如像这样:

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

3
投票

此问题首先出现在Google上,没有适当的答案。

由于简单格式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的解决方案:

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


2
投票

将此添加到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。


0
投票

这里是另一种变化:

= f.label :some_param, class: "label__class" do
  = f.input_field :some_param, class: "checkbox__class"
  Label text
© www.soinside.com 2019 - 2024. All rights reserved.