2016-04-22 86 views
0

我有以下部分:軌道4:渲染部分具有可變

<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...。我知道這不是提供變量的正確方法,但我應該怎麼做?

回答

3

不能嵌套ERB標籤是這樣的:

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

而是這樣做:

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

無論你把ERB標籤裏面的紅寶石。所以你的代碼是說:「運行Ruby代碼week.<%= field,並堅持在這裏結果。」但是這不是有效的Ruby語法。

或者,如果field包含屬性的名稱,你可以這樣做:

<%= week.send field.to_sym %> 
0

不能嵌套ERB標籤。 如果你的變量是字符串,你可以連接它們。

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

如果拋出一個錯誤試試這個

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