SimpleForm maxlength扩展如何工作

时间:2013-02-25 09:11:46

标签: ruby-on-rails ruby-on-rails-3 simple-form

我想在SimpleForm gem的帮助下创建表单上输入的maxlength html属性。我知道我可以通过在创建表单时手动传递maxlength属性来完成此操作,例如:

<%= f.input :username, input_html: { maxlength: 20 } %>

但这不是我想要的,因为根据SimpleForm配置文件中的注释,你应该启用maxlength扩展,当给出最大长度验证时,它会自动将这个html属性添加到字符串属性的输入标记。

## Optional extensions
# They are disabled unless you pass `f.input EXTENSION_NAME => :lookup`
# to the input. If so, they will retrieve the values from the model
# if any exists. If you want to enable the lookup for any of those
# extensions by default, you can change `b.optional` to `b.use`.

# Calculates maxlength from length validations for string inputs
b.use :maxlength

不幸的是,上面提到的两种可能性都不起作用。我是否完全误解了maxlength扩展的使用?

1 个答案:

答案 0 :(得分:11)

将simple_form.rb配置文件编辑为

时,这是正确的
b.use :maxlength

表单中的max-length将使用模型外的值。

我将simple_form与Twitter Bootstrap结合使用。为了在表单上产生这种效果,我还必须在配置文件simple_form_bootstrap.rb中插入此行

# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
   config.wrappers :bootstrap, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|

   # Calculates maxlength from length validations for string inputs
   b.use :maxlength
   ...