簡體   English   中英

nil的未定義方法`code':帶有rails和遺留數據庫的NilClass消息

[英]undefined method `code' for nil:NilClass message with rails and a legacy database

我正在設置一個非常簡單的rails 3應用程序來查看舊MySQL數據庫中的數據。 遺留數據庫主要是rails ORM兼容,除了外鍵字段是多元化的。 例如,我的“訂單”表有一個名為“companies_id”的“公司”表的外鍵字段(而不是“company_id”)。 所以很自然地我必須使用“belongs_to”的“:foreign_key”屬性來手動設置字段名稱。

我幾年沒用過rails,但我很確定我做的一切都正常,但是在嘗試訪問“order.currency.code”時遇到以下錯誤:

undefined method `code' for nil:NilClass

到目前為止,這是一個非常簡單的應用。 我唯一做的就是為每個遺留數據庫表生成應用程序和一堆腳手架。 然后我進入了一些模型進行調整以適應上述數據庫命名約定的差異,並在視圖中添加了一些字段。 而已。 沒有好笑的事。

所以我的數據庫表看起來像這樣(僅限相關字段):

orders
------
id
description
invoice_number
currencies_id

currencies
----------
id
code
description

我的訂單模型如下所示:

class Order < ActiveRecord::Base
  belongs_to :currency, :foreign_key=>'currencies_id'
end

我的貨幣模型如下所示:

class Currency < ActiveRecord::Base
    has_many :orders
end

相關的視圖片段如下所示:

<% @orders.each do |order| %>
  <tr>
    <td><%= order.description %></td>
    <td><%= order.invoice_number %></td>
    <td><%= order.currency.code %></td>
  </tr>
<% end %>

我完全沒有想法。 有什么建議?

或者因為你在使用ruby 1.9.2運行的rails 3應用程序中,你也可以使用orer.currency.try(:code)來獲取這些可能為零的屬性。 尼基塔雷巴克指出錯誤

在大多數情況下,這是因為沒有設置某些訂單的外鍵。 你可以在你的視圖中處理它

<%= order.currency.nil? ? 'no currency' : order.currency.code %>

或者只是簡單的<% if order.currency.nil? %> ... <% else %> ... <% end %> <% if order.currency.nil? %> ... <% else %> ... <% end %>

要檢查,您可以在錯誤行之前打印外鍵( currencies_id )的值到日志。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM