ActionView :: Template :: Error(未定义的方法`currency' for nil:NilClass):

时间:2014-06-25 11:00:31

标签: ruby-on-rails ruby-on-rails-3

我有一段看起来像这样的代码;

<% @current_user.prices.each_with_index do | t, i| %>
    <tr>
        <td> <%= (i+1) %> </td> 
        <td> <%= t.country %> </td>
        <td> <%= t.network %> </td>
        <td> <%= t.send("price_#{@current_user.currency.downcase}") %> </td>
    </tr>       
<% end %>

但是它给出了错误;

ActionView::Template::Error (undefined method `currency' for nil:NilClass):
    30:                             <td> <%= (i+1) %> </td> 
    31:                             <td> <%= t.country %> </td>
    32:                             <td> <%= t.network %> </td>
    33:                             <td> <%= t.send("price_#{@current_user.currency.downcase}")  %> </td>
    34:                         </tr>       
    35:                     <% end %>
    36:                 <% else %>
  app/views/prices/index.html.erb:33:in `block in _app_views_prices_index_html_erb__1511544251155426207_16153880'
  app/views/prices/index.html.erb:28:in `_app_views_prices_index_html_erb__1511544251155426207_16153880'

然而,在一个非常类似的情况下它运作得很好;

<% @current_user.prices.each_with_index do | t, i| %>
    <tr>
       <td> <%= (i+1) %> </td> 
       <td> <%= t.country %> </td>
       <td> <%= t.network %> </td>
       <td> <%= t.send("price_#{@current_user.currency.downcase}") %> </td>
   </tr>    
   

它是如何在一个场景中起作用而不是另一个场景?也许我只是累了。

3 个答案:

答案 0 :(得分:0)

对于一个用户,它具有除了nil之外的某些值,对于当前用户,货币的值为零,为什么会出现此错误,您可以使用控制台检查或应用断点并检查当前用户货币值

答案 1 :(得分:0)

您的@current_user变量似乎为零,并且您正在为该零对象调用货币。

<强>解

如果您只想跳过此错误,则可以使用try(),如下面的代码。

示例:

@current_user.try(:currency).try(:downcase)
# try() behaves something like ternary operator (if then else)

但是,我建议您为@current_user指定所需的值。因为如果你使用try(),如果父对象是nil,它将返回nil。因此,调试@current_user变量并为其指定正确的值。

答案 2 :(得分:0)

@current_user.currency.downcase无效,因为index controller未使用设计进行身份验证,因此未定义@current_user

但是,我无法解释为什么在这一行之上定义了几行。

相关问题