Forum: Ruby on Rails Having nil / non-nil relationships

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
jasonlee9 (Guest)
on 2005-11-25 23:06
(Received via mailing list)
Hi all,

I have a problem I'm trying to figure out. I have a table/object that
can have either a nil or non-nil id that points to another table. For

| id           | <- not null
| name         | <- not null
| company_id   | <- nullable
| company_name | <- nullable

| cid           |
| name          |

So I want to be able to allow a customer to either select a company
name from a drop down list, or enter a name we don't have in the
database, or not have to enter a name at all. In my Customer class
I'm trying a

has_one :company, :foreign_key => "cid" # I know there is no FK

but the sql comes out saying something like

SELECT * FROM companies WHERE ( companies.cid = 3251 ) LIMIT 1

where 3251 is the id of the Customer obj/table. So AR looks like it's
trying to fetch me the association, but it's using the Customers
table id as the PK id for the Companies table, which I don't want. If
I *must* have a FK from Customers.company_id -> Companies.cid I
suppose I can pass in a -1 default when the user does not select or
use a company (will AR do this??), but I was kinda hoping I wouldn't
have to. It would just seem nice to check for a nil
customer.company_id and then display the or not.

Any suggestions? Thanks,

- jason
christopher.k.hall (Guest)
on 2005-11-26 04:20
(Received via mailing list)
Why not just use 'id' instead of 'cid' as the column name in the
Pete Y. (Guest)
on 2005-11-26 06:45
(Received via mailing list)
For starters, you want a "belongs_to" relationship rather than a
"has_one" relationship.

jasonlee9 (Guest)
on 2005-11-26 19:35
(Received via mailing list)
You're right, that works. However, I guess, after reading many times,
I still don't quite grasp the difference (in my case) between using
has_one and belongs_to. I would think that customer would have one
company and not 'belong' to a company; I would think, if anything,
that employee would belong to a company.

I suppose I need to really connect in my mind what AR is actually
doing with a belongs_to. Anyway, for now, this works correctly and I
guess until it really sinks in I'll try has_one and if that doesn't
work, belongs_to.


- jason
christopher.k.hall (Guest)
on 2005-11-26 20:39
(Received via mailing list)
the simple way to remember is this:

if table A contains a reference (the *_id column) to table B, then model
belongs_to Model B and Model B has_many or has_one Model A.
This topic is locked and can not be replied to.