0
votes

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.

1

1 Answers

2
votes

What about:

<%= form_for @tube do |f| %>
  <% @tube.attribute_names.each do |attr| %>
    <%= f.text_field attr, :class=>'std_input' %>
    <%= f.label attr, :class=>'std_label' %>:
  <% end %>
<%= f.submit %>
<% end %>