0

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 Answer 1

2

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 %>
Sign up to request clarification or add additional context in comments.

2 Comments

apneadiving, you rock. That works perfectly, thank you. I have to study this more and get the difference between ".each do |x|" and ".each{|x| ... }" solidly in my head.
glad to know it helped. There is no difference between the two way of coding you present, just a matter of taste.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.