user6128363
user6128363

Reputation:

Dynamically displaying the column values

Here, I have 10 columns i.e., answer1, answer2, answer3, ..., answer10 in the table MgAnswer. I have to check whether each column value is present or not. Only if it present,then I have to display it in the page.

Im giving column names dynamically within for loop

<% (1..10).each do |i| %>
   <% if MgAnswer."answer#{i}".present? %>
      <%= MgAnswer."answer#{i}" %>
   <% end %>
<% end %>

Im ending up with Syntax error.

Upvotes: 0

Views: 62

Answers (2)

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

It should seem like the following:

<% (1..10).each do |i| %>
  <%= MgAnswer.send("answer#{i}") %>
<% end %>

Since ruby can't evaluate line as MgAnswer."method". Also you can just skip if condition, because it will be evaluated to empty string "".

Upvotes: 2

ndnenkov
ndnenkov

Reputation: 36101

You can indeed dynamically invoke methods in ruby, but this is not the syntax. Instead do

<% (1..10).each do |i| %>
  <% if MgAnswer.public_send("answer#{i}").present? %>
    <%= MgAnswer.public_send("answer#{i}") %>
  <% end %>
<% end %>

Upvotes: 3

Related Questions