使用simple_form添加复选框而不与模型关联?

Mik*_*hko 26 haml ruby-on-rails 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'
Run Code Online (Sandbox Code Playgroud)

Gac*_*cha 36

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

class Resource < ActiveRecord::Base
  attr_accessor :custom_field
end
Run Code Online (Sandbox Code Playgroud)

然后使用此字段作为块:

= f.input :custom_field, :label => false do 
  = check_box_tag :some_name
Run Code Online (Sandbox Code Playgroud)

尝试在他们的文档中找到"Wrapping Rails Form Helpers" https://github.com/plataformatec/simple_form

  • 这是一个有用的答案,应该接受恕我直言 (3认同)

huo*_*ito 34

你可以用

f.input :field_name, as: :boolean
Run Code Online (Sandbox Code Playgroud)

  • 如果`field_name`没有在模型中定义它不会工作,请注意`没有与model关联` (14认同)

m4r*_*73n 15

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

但是,如果使用:input_html参数为字段指定默认值,则它可以工作,例如:

= f.input :custom_field, :as => :boolean, :input_html => { :checked => "checked" }
Run Code Online (Sandbox Code Playgroud)