10

这是一个我有点羞于问的简单问题,但我一直把头撞在墙上并浏览rails 3文档但没有任何成功:/

所以,事情是这样的:

当我使用fields_for助手时,它会将生成的字段包装在<div class="fields"> ... </div>标签中。

所以,我的代码是

<ul class="block-grid two-up">
  <%= f.fields_for :images do |image_builder| %>
    <%= render "images/form", :f => image_builder %>
  <% end %>
</ul>

生成的html是:

<ul class="block-grid two-up">
  <div class="fields">
    <div>
      <label for="company_images_attributes_0_image"> Image</label>
      <input id="company_images_attributes_0_image" 
             name="company[images_attributes][0][image]" type="file">
    </div>
  </div>
  <div class="fields">
    <div>
      <label for="company_images_attributes_1_image"> Image</label>
      <input id="company_images_attributes_1_image" 
             name="company[images_attributes][1][image]" type="file">
    </div>
  </div>
</ul>

我想要做的实际上是将<div class="fields">包装标签更改为<li>.

文档说您可以将选项传递给fields_for,但不清楚您可以传递哪些选项,也许您可​​以更改此包装标签?

一种可能是覆盖一个函数,有点像ActionView::Base.field_error_proc表单中有错误时。

快速编辑:我忘了提到我正在使用 simple_form 来生成这个表单。我尝试在simple_form.rb配置文件中寻找一种自定义方法,但我没有看到任何方法。

解决方案 经过进一步调查,事实证明该表单也使用nested_form gem 来生成表单(不仅仅是simple_form)。这个生成器导致 fields_for 被包装在 div 标签中。感谢大家的建议!

4

3 回答 3

12

以下禁用包装器:

f.fields_for :images, wrapper:false do |image_builder|

然后您可以在构建器块中添加自己的包装器。

于 2014-09-25T04:24:26.293 回答
2

一个便宜的解决方案就是<li>在表单中添加标签,例如:

<%= f.fields_for :images do |image_builder| %>
 <li><%= render "images/form", :f => image_builder %></li>
<% end %>

我不确定您是否可以通过将一些参数传递给field_for. 但我认为您可以通过传递 html 块来更改 div 类或 id 的名称,例如form_for

<%= form_for @image, :as => :post, :url => post_image_path, 
   :html => { :class => "new_image", :id => "new_image" } do |f| %>
于 2012-01-20T03:14:49.117 回答
-1

你说你正在使用 simple_form 那么你应该说<%= f.simple_fields_for... 您是否尝试过使用wrapper_html选项:

<%= f.input :name, :label_html => { :class => 'upcase strong' },
  :input_html => { :class => 'medium' }, :wrapper_html => { :class => 'grid_6 alpha' } %>

编辑 1: 来自 SimpleForm 文档:

包装器

SimpleForm允许您添加一个包含标签、错误、提示和输入的包装器。第一步是配置一个包装标签:

SimpleForm.wrapper_tag = :p

现在,您不再需要包装 f.input 调用了:

<%= simple_form_for @user do |f| %>
  <%= f.input :username %>
  <%= f.input :password %>
  <%= f.button :submit %>
<% end %>

编辑2:

并且有这个配置选项,您可以使用它来说明与包装器元素一起使用的 css 类:

配置/初始化程序/simple_form.rb

# CSS class to add to all wrapper tags.
config.wrapper_class = :input
于 2012-01-20T07:51:53.590 回答