Forum: Ruby on Rails AR foreign key problem.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Gijs N. (Guest)
on 2006-05-24 17:49
(Received via mailing list)
Hello Railslist,

(I'm using RadRails 0.6.3 on Windows XP with Ruby 1.8.4, Rails 1.1 and
SQLite3)

I have two tables in the database: "locations" and "customers":

customers.sql
---
id INT PRIMARY KEY
name VARCHAR 255
address VARCHAR 255
postal_code VARCHAR 255
city VARCHAR 255
---

locations.sql
---
id INT PRIMARY KEY
postal_code TEXT
longitude FLOAT
latitude FLOAT
---


I've created two models (customer.rb and location.rb):

customer.rb
---
class Customer < ActiveRecord::Base
  belongs_to :location, :foreign_key=>'postal_code'
  validates_presence_of :name, :postal_code
end
---

location.rb
---
class Location < ActiveRecord::Base
  has_many :customers
end
---

The locations table is filled with >300,000 records.
The customers table has a couple of records with postal_codes that
match the locations table.

In the controller, I have...
---
  def test
    @customer = Customer.find(1)
  end
---

In the view, I have...
---
<%= @customer.name %>
---
...which yields the first name-record in the customers table, so that's
OK.

But shouldn't I be able to now do something like:
---
<%= @customer.location.latitude %>
---
...and expect it to return the corresponding latitude from the locations
table?

I get the nil error:
---
"You have a nil object when you didn't expect it!
The error occured while evaluating nil.latitude"
---

What could be wrong?
Is it something with the way I've set up the alternative foreign-key?
or is it a plural/singular naming problem?

Thanks for any help.

Gijs N.
unknown (Guest)
on 2006-05-24 18:11
(Received via mailing list)
Replace the postal_code field in customers with a postal_code_id int
field, then you should be able to get that working.
-N
Gijs N. (Guest)
on 2006-05-24 18:54
(Received via mailing list)
does the table postal_code_in need to be of type INT per se?
I still get exactly the same error (nil object) as before (I restarted
webrick)
jatinder saundh (Guest)
on 2006-05-25 10:27
(Received via mailing list)
1. postal_code column in both the tables should be of same type
if that is not working then having a location_id column in customers
table,
referring to id column of locations table will surely work; with this
you
can skip :foreign_key option, Rails will take care of that.

Regards,
Jatinder
unknown (Guest)
on 2006-05-25 17:01
(Received via mailing list)
Oh yeah, that's what I meant. I was thinking you had a postal_codes
table, because I've got one of those. But using an int location_id
would do the job.
-N
This topic is locked and can not be replied to.