2012-02-07 34 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。