umezo
umezo

Reputation: 1579

How to loop through attributes and an array to create a table in a form

I'm creating a survey, and have a bunch of columns named :movie_1 through :movie_5 that I would like to loop through to make a table in my form. What is the best way to do so?

So far I have started out as below, but can't figure out how to format the loop.

survey.rb model

attr_accessible :movie_1, :movie_2, :movie_3, :movie_4, :movie_5

MOVIES = ["Rocky", "Wayne's World", "The Godfather", "Alien", "Toy Story"]

new.html.erb survey form

<%= form_for @survey do |f|
  <table>
    <tr>
      <th>Movie Name</th>
      <th>Rating</th>
    </r>
    <% 5.times.each do |n| %>
      <tr>
        <th><%= f.label Survey::MOVIES[n] %></th> # how can I loop through the MOVIES array?
        <th><%= f.text_field :movie_n %></th> # how can I loop through the different columns?
      </tr>
    <% end %>
  </table>
<% end %>

Upvotes: 2

Views: 1213

Answers (3)

scones
scones

Reputation: 3345

You can loop through the column and just use those, that match the naming pattern.

example

Survey.columns.select{|c| c if c =~ /movie_[0-9]/}.each { |movie_column| puts movie_column }

But the better solution would be to have the correct relations setup, like mind.blank describes.

Upvotes: 2

Mischa
Mischa

Reputation: 43298

This should work:

<% Survey::MOVIES.each_with_index do |movie, index| %>
  <tr>
    <th><%= f.label movie %></th>
    <th><%= f.text_field "movie_#{index+1}".to_sym %></th>
  </tr>
<% end %>

However mind.blank is right: it's bad design to have movie_1, movie_2, etc fields in your survey model. It would make much more sense to have a movie model that belongs to a survey.

Upvotes: 1

mind.blank
mind.blank

Reputation: 4880

In this case you might want to consider making another model Movie which belongs to Survey and then use nested forms to display all the movies / update them.

There's a few good railscasts here about nested forms.

Upvotes: 5

Related Questions