Home > Net >  Ruby on Rails - Creating rows in an html.erb table by looping over instance variable
Ruby on Rails - Creating rows in an html.erb table by looping over instance variable

Time:03-24

I have an instance variable @referrals which contains names of referrals a person has done. I now need to create a table showing all these referrals as rows. I have tried the following code in the html.erb file:

<table style="border:1px solid black;margin-left:auto;margin-right:auto;">
      <th> Referral Emails </th>
      <% @referrals.each do |referrals| %>
        <tr> referrals </tr>
     <%end %>
</table>

and

<table style="border:1px solid black;margin-left:auto;margin-right:auto;">
      <th> Referral Emails </th>
      <% @referrals.each do |referrals| %>
        <%= <tr> referrals </tr> %>
     <%end %>
</table>

Both show up errors.

I am new with Ruby, help with the correct Ruby code is much appreciated. Thanks a ton in advance.

Edits: Code changes as suggested by @mu is too short.

CodePudding user response:

By default in ERB, code blocks are enclosed in <% and %> delimiters, and if you want the result of the code block run, you use the = symbol inside, like <%= 'Hel' 'lo' %>, world would output "Hello, world".

Each member being iterated over with .each is named between the pipe symbols, so that is what you reference inside the block.

Also table rows need to have table data, or <td> tags within the row <tr> tags.

Here's what should work for you assuming that @referrals is a list of strings:

<table style="border:1px solid black;margin-left:auto;margin-right:auto;">
  <tr> <th> Referral Emails </th> </tr>
  <% @referrals.each do |referral| %>
    <tr> <td> <%= referral %> </td> </tr>
  <% end %>
</table>
  • Related