开发者

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

开发者 https://www.devze.com 2023-02-05 00:21 出处:网络
I\'m setting up a very simple rails 3 application to view data in a legacy MySQL database. The legacy database is mostly rails ORM compatible, except that foreign key fields are pluralized. For exampl

I'm setting up a very simple rails 3 application to view data in a legacy MySQL database. The legacy database is mostly rails ORM compatible, except that foreign key fields are pluralized. For example, my "orders" table has a foreign key field to the "companies" table called "companies_id" (rather than "company_id"). So naturally I'm having to use the ":foreign_key" attribute of "belon开发者_开发百科gs_to" to set the field name manually.

I haven't used rails in a few years, but I'm pretty sure I'm doing everything right, yet I get the following error when trying to access "order.currency.code":

undefined method `code' for nil:NilClass

This is a very simple application so far. The only thing I've done is generate the application and a bunch of scaffolds for each of the legacy database tables. Then I've gone into some of the models to make adjustments to accommodate the above mentioned difference in database naming conventions, and added some fields to the views. That's it. No funny business.

So my database tables look like this (relevant fields only):

orders
------
id
description
invoice_number
currencies_id

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

My Order model looks like this:

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

My Currency model looks like this:

class Currency < ActiveRecord::Base
    has_many :orders
end

The relevant view snippet looks like this:

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

I'm completely out of ideas. Any suggestions?


Or since you are in rails 3 app which runs on ruby 1.9.2, you could also use orer.currency.try(:code) for such attributes which can be potentially nil. And the error is as pointed out as by Nikita Rybak


In most cases, that happens because foreign key for some order isn't set. You can handle it in your view like this

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

Or just plain <% if order.currency.nil? %> ... <% else %> ... <% end %>

To check, you can print value of foreign key (currencies_id) to a log, right before error line.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号