简体   繁体   中英

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

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM