Search code examples
ruby-on-rails-4iteratormodelattribute

how to iterate over all strings in a single record


I have a model called train that has 240 strings in it. Each string is simply named S1 through S240. I am wondering if there is a way to iterate over each string in a single record. I have a view that displays the strings. Some of the strings will have something in them and some will be empty and I just want to display the ones that are not empty in view. So I need an iterator or something to check each one and see if it is empty or not and display it if it's not empty.

I can do it using this:

<% if @train.s1 != nil then %>
  <%= @train.s1 %><br>
<% end %>

Obviously I don't want to do that for 240 strings.


Solution

  • You probably can do something like iterating over the model's attributes.

    <% @train.attributes.each do |attr_name, attr_value| %>
      <% !if attr_value.blank? %>
        <%= attr_value %>
      <% end %>
    <% end %>
    

    This won't really work for you if you have more attributes than just those strings. Why don't you work with an association? Train has_many Strings and String belongs_to Train. So you could then iterate over @train.strings.each?