3

:size => nil我看到自己为此写了很多f.text_field

<%= f.text_field :street_address, :size => nil %>
<%= f.text_field :post_code, :size => nil %>
<%= f.text_field :city, :size => nil %>

这只是愚蠢的。如果没有:size => nil上述内容, text_field 会呈现<input>一个size="some number"(通常size="30")我不需要或不想要的。

那么,如何实现 DRY 并使其默认f.text_field不会生成size=30orsize="some number"属性?这样我就可以避免总是不得不输入:size => nil.

4

4 回答 4

4

所有默认字段选项都存储在一个哈希中。它默认为以下内容:

# action_view/helpers/form_helper
DEFAULT_FIELD_OPTIONS = { "size" => 30 }

例如,您可以在初始化程序中从中删除“大小”。

ActionView::Helpers::InstanceTag::DEFAULT_FIELD_OPTIONS.delete("size")
于 2012-09-16T10:55:07.800 回答
4

with_optionsRails 使用方法扩展了 Object 类。您可以利用它:

<%= form_for :foo do |f| %>
    <% f.with_options :size => nil do |f_nil| %>
        <%= f_nil.text_field :street_address %>
        <%= f_nil.text_field :post_code %>
        <%= f.text_field :city %> <!-- you can use old f here too! -->
    <% end %>
<% end %>

给出:

<input id="foo_street_address" name="foo[street_address]" type="text" />
<input id="foo_post_code" name="foo[post_code]" type="text" />
<input id="foo_city" name="foo[city]" size="30" type="text" /> <!-- you can use old f here too! -->
于 2012-09-16T11:08:03.490 回答
0

尝试像这样封装 text_field:

def no_size_text_area(form, method) form.text_area(method, {:size => nil}) end

把函数放在你的帮助文件中。

并在其位置使用 no_size_text_area ,如下所示:

no_size_text_area(f,:city)
于 2012-09-16T10:21:49.897 回答
0

Rails 团队已经从 version 中删除了这些默认值4.0.x。也无法再设置全局默认值。唯一简单的解决方案是使用 CSS 来设置尺寸。

于 2016-09-15T22:59:32.977 回答