Rails通过表单字段中的数据循环 [英] Rails loop through data in a form field

查看:156
本文介绍了Rails通过表单字段中的数据循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过我的表单中的数据库中的数据循环。我想要处理的数据放在标签和文本框中。我怎么能在轨道上做到这一点?我只是使用一个.each块来循环通过它的形式内?我在我的数据库中的原因是因为我的客户希望能够自己添加表单字段数据。






例如这里是我想要做的事情:

 <%= form_for:order do | f | %GT; 
@ fields.each do | field |
<%= f.label field.name%>
<%= f.text_field field.name%>
<%end%>
<%= f.submit%>
<%end%>

完成此类操作的最佳方法是什么?

$ p
$ b $ p


解决方案

 < / p> 

%= form_for:order do | f | %GT;
<%@ fields.each do | field | %GT;
<%= f.label field.name%>
<%= f.text_field field.name%>
<%end%>
<%= f.submit%>
<%end%>

如果您需要比标签/文本字段对更复杂的东西,那么您可以使用部分-template并使用collection关键字:

 <! -  in order.html.erb' - > 
<%= form_for:order do | f | %GT;
<! - 注意:每个'字段'是从集合/部分名称中自动填充的,但是您需要将表单作为本地 - >
<%= render:partial => 'field',:collection => @fields,:locals => {:f => f}%>
<%= f.submit%>
<%end%>

 <! -  in'_field.html.erb' - > 
<%= f.label field.name%>
<%= f.text_field field.name%>
<! - 以及其他你想做的事情 - >

更多关于部分呈现的信息: http://api.rubyonrails.org/classes/ActionView/Partials.html


I would like to loop through data in my database inside my form. What I would like to do with the data is put it in labels and textboxes. How could I do this in rails? Would I just use a .each block to loop through it inside the form? The reason I have it in my database is because my client would like to be able to add the form field data himself.


For example here is something I would like to do:

<%= form_for :order do |f| %>
  @fields.each do |field|
    <%= f.label field.name %>
    <%= f.text_field field.name %>
  <% end %>
  <%= f.submit %>
<% end %>

What the best way to accomplish something like this?

Please don't answer with a railscast :)

Thanks in advance

解决方案

Yes, that will work, though you missed an end script tag on line two:

<%= form_for :order do |f| %>
   <% @fields.each do |field| %>  
       <%= f.label field.name %>
       <%= f.text_field field.name %>
   <% end %>
   <%= f.submit %>
<% end %>

If you need something more complex than just a label/text field pair - then you can use a partial-template and use the collection keyword:

<!-- in 'order.html.erb' -->
<%= form_for :order do |f| %>
   <!-- note: each 'field' is auto-populated from the collection/partial-name, but you need to pass the form in as a local -->
   <%= render :partial => 'field', :collection => @fields, :locals => {:f => f} %>  
   <%= f.submit %>
<% end %>

and

<!-- in '_field.html.erb' -->
<%= f.label field.name %>
<%= f.text_field field.name %>
<!-- and whatever else you want to do... -->

more on partial rendering here: http://api.rubyonrails.org/classes/ActionView/Partials.html

这篇关于Rails通过表单字段中的数据循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆