Rails 4:使用变量渲染部分

时间:2016-04-22 16:46:58

标签: ruby-on-rails partial-views partials

我有以下部分内容:

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

...我希望能够提供2个变量attributefield。当我尝试使用以下内容渲染部分时:

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

......我想:

<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>

...但是syntax error, unexpected tOP_ASGN...失败了。我知道这不是提供变量的正确方法,但我该怎么做呢?

2 个答案:

答案 0 :(得分:3)

你不能像这样嵌套ERB标签:

int status;
try{
    Bundle b = getIntent().getExtras();
    status = b.getInt("status");
} catch(Exception ex){
    status = -1; //Or some error status //
}

而是这样做:

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

你在ERB标签里面放的是Ruby。所以你的代码说“运行Ruby代码<%= week %>.<%= field %> 并将结果粘贴在这里。”但这不是有效的Ruby语法。

如果week.<%= field包含属性的名称,您可以执行以下操作:

field

答案 1 :(得分:0)

您无法嵌套erb标记。 如果您的变量是字符串,则可以将它们连接起来。

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

如果出现错误,请尝试此

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