“未定义的方法`[]'为nil:NilClass”

时间:2015-06-04 08:54:22

标签: ruby-on-rails ruby

<% 
 @loans.each do |loan_rec| 
  loan=loan_rec.info 
  if loan['_LoanName'].blank?
    loan_name = 'No Loan Title'
  else
    loan_name = loan['_LoanName']
  end
end
%>

我收到undefined method `[]' for nil:NilClass的错误。什么是未定义的?当我在循环中打印loan数组时,它会得到以下结果:

{
  "_LendingCategory"=>"Private Real Estate Loan",
  "Email"=>"entregeorge@gmail.com",
  "FirstName"=>"TestDavid",
  "Id"=>3573,
  "_LoanName"=>"null",
  "LastName"=>"TestGeorge",
  "_DesiredTermLength"=>"3",
  "_TransactionType0"=>"Purchase",
  "_CashContribution"=>100000.0,
  "_NetLoanAmountRequested0"=>8000000.0
}

3 个答案:

答案 0 :(得分:3)

至少有一个Loan loan_rec.infonil。你可以尝试:

loan = loan_rec.info || Loan.new

作为快速修复,但您还应该弄清楚如何首先避免使用nil

答案 1 :(得分:1)

<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MyFirstMNCActivity"> <group android:id="@+id/grp1"> <item android:id="@+id/navigation_item_1" android:checked="true" android:icon="@drawable/ic_home" android:title="@string/navigation_item_1" /> </group> <group android:id="@+id/grp2"> <item android:id="@+id/navigation_item_2" android:icon="@drawable/ic_home" android:title="@string/navigation_item_2" /> </group> </menu> 中,没有任何loan键。所以你会得到一个info值。

答案 2 :(得分:1)

您需要预计每info可能没有loan_rec。我会像这样重构你的代码:

<% 
  @loans.each do |loan_rec| 
    loan = loan_rec.info 
    loan_name = loan && loan['_LoanName']
    if loan_name.blank?
      loan_name = 'No Loan Title'
    end
  end
%>