Having nil / non-nil relationships


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 customer.company or not.

Any suggestions? Thanks,

  • jason


Why not just use ‘id’ instead of ‘cid’ as the column name in the


For starters, you want a “belongs_to” relationship rather than a
“has_one” relationship.



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


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.