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.