2012-02-07 37 views
24

如何使用simple_form添加复选框而不与模型关联? 我想创建复选框,它将处理一些javascript事件,但不知道? 也许我错过了文档中的东西? Want't使用类似像下面:用simple_form添加复选框而不与模型关联?

= 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' 
+0

如果此复选框与模型没有关联为什么不使用standart复选框助手? http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag – 2012-02-07 19:21:55

+0

我懒得使用各种CSS) – 2012-02-07 19:46:53

+0

我不认为你可以使用simple_form助手没有记录字段。不要使用simple_form为你的复选框生成的类,你不需要添加自定义的CSS。我注意到你是来自塞瓦斯托波尔进入我们当地的塞瓦斯托波尔.rb聚会在这天!干杯! – 2012-02-07 21:21:07

回答

34

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

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

+0

这节省了我很多麻烦。非常感谢。 – 2013-08-05 13:26:20

+3

这是一个有用的答案,应该接受恕我直言 – hananamar 2013-09-12 15:23:29

31

你可以使用

f.input :field_name, as: :boolean 
+0

这应该是被接受的答案 – 2014-03-18 15:28:45

+14

请注意'与模型无关 如果'field_name'没有在它不会工作的模型中定义 – Muntasim 2014-06-30 05:26:25

12

通过huoxito提出的命令不工作(至少在轨道4,5)。据我推测,错误是由Rails试图查找:custom_field的默认值引起的,但由于该字段不存在,此查找失败并引发异常。

但是,如果指定使用:input_html参数字段的默认值,它的工作原理,如像这样:

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

这个问题首先在谷歌没有适当的答案。

由于简单的表单3.1.0.rc1有这样做的一个适当的方式对维基解释说: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。