Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 "belongs_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?

like image 791
Jude Osborn Avatar asked Mar 05 '26 04:03

Jude Osborn


1 Answers

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

like image 137
Kunday Avatar answered Mar 07 '26 21:03

Kunday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!