Jeremy Thomas
Jeremy Thomas

Reputation: 6674

Rails 4: Render partial with variable

I have the following partial:

<tr class="profile-row">
    <td class="profile-header"><%= attribute %></td>
    <% for week in @weeks %>
    <td><%= week.<%= field %> %></td> <!-- where it fails -->
    <% end %>
</tr>

...and I'd like to be able to supply 2 variables, attribute and field. When I try to render the partial with the following:

<%= render 'foo', attribute: 'Current Weight', field: 'current_weight' %>

...I want:

<tr class="profile-row">
    <td class="profile-header">Current Weight</td>
    <% for week in @weeks %>
    <td><%= week.current_weight %></td> <!-- where it fails -->
    <% end %>
</tr>

...but this fails with syntax error, unexpected tOP_ASGN.... I understand this isn't the correct way to supply a variable, but how should I do it?

Upvotes: 0

Views: 102

Answers (2)

coderVishal
coderVishal

Reputation: 9079

You cannot nest erb tags. If your variables are strings you can concatenate them.

<%= week + "." + field%>

If that throws an error try this

<%= week.to_s + "." + field.to_s%>

Upvotes: 0

Paul A Jungwirth
Paul A Jungwirth

Reputation: 24541

You can't nest ERB tags like this:

<%= week.<%= field %> %>

Instead do this:

<%= week %>.<%= field %>

Whatever you put inside ERB tags is Ruby. So your code is saying "Run the Ruby code week.<%= field and stick the result here." But that is not valid Ruby syntax.

Or if field contains the name of the attribute, you could do this:

<%= week.send field.to_sym %>

Upvotes: 3

Related Questions