Rails:循环数组以创建输出
我有一个模型“管”,它是一个包含真空管各种数据的数据库。我想动态循环所有列并为我的“新”和“编辑”页面创建一个基本表。 我获取这样的属性名称:
<% attr_array = @tube.attribute_names %>
我想做这样的事情:
<% attr_array.each{|x|文本字段:x } %>
希望动态生成这个:
<%= form_for @tube do |f| %> <%= f.label :name, :class=>'std_label' %>:
<%= f.text_field :name, :class=>'std_input' %>
<%= f.label :function_class, :class=>'std_label' %>:
<%= f.text_field :function_class, :class=>'std_input' %>
<%= f.label :base_type, :class=>'std_label' %>:
<%= f.text_field :base_type, :class=>'std_input' %>
……等等…… <%= f.submit %> <%结束%>
但当然这是行不通的,至少是行不通的。如何根据 attribute_names 数组动态生成 text_field 输入?我使用的表有大约 30 个属性,我认为手动构建它们是愚蠢的,特别是考虑到如果它们将来发生变化,那么代码就会崩溃。谷歌搜索和阅读 API 让我了解了为什么这行不通,但也让我对代码示例感到兴奋,了解它的作用。
准确的帮助表示赞赏。
I have a model "tube" which is a database having the various data for vacuum tubes. I want to dynamically loop through all the columns and create a basic table for my "new" and "edit" pages.
I grab the attribute names like this:
<% attr_array = @tube.attribute_names %>
And I want to do something like this:
<% attr_array.each{|x| text_field :x } %>
in hopes of dynamically generating this:
<%= form_for @tube do |f| %>
<%= f.label :name, :class=>'std_label' %>:
<%= f.text_field :name, :class=>'std_input' %>
<%= f.label :functional_class, :class=>'std_label' %>:
<%= f.text_field :functional_class, :class=>'std_input' %>
<%= f.label :base_type, :class=>'std_label' %>:
<%= f.text_field :base_type, :class=>'std_input' %>
.... and so forth ....
<%= f.submit %> <% end %>
But of course this does not work, not by a long shot. How can I generate my text_field inputs dynamically based on the attribute_names array? The table I am using has about 30 attributes and I think it's silly to build them all by hand, especially given that if they change in the future then the code will break. Googling and reading the API have given me the lectures on why this doesn't work, but has left me hi and dry with a code example of what does.
Accurate help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
怎么样:
What about: