Topic: has_one vs. has_many

I have two tables costs and vendor_items.  costs has a field vendoritemid that relates to the itemid field in vendor_items.  vendor_items also has a desc field.  I would like to refer to the desc field like this:

cost.vendor_item.desc

First I tried this in the costs model:

has_one :vendor_item, :foreign_key => vendoritemid

but that didn't work because the relation is not through the vendor_items' primary key (id).   I then tried this:

has_many :vendor_item, :finder_sql => 'select * from vendor_items where itemid = \"#{vendoritemid}\"'

This worked but because it returned an array (even though there is only one vendor_item row per cost row) I had to reference it like this:

cost.vendor_item[0].desc

which worked ok.  But this seems kind of clunky.   

Is there some way to do a has_one where you can use a different set of fields for the association than the "normally" associated fields i.e. costs.vendor_item_id and vendor_items.id?

Re: has_one vs. has_many

If you rename the "itemid" column in the vendor_items table to "id", and rename the "vendoritemid" column in the costs table to "vendor_item_id" you can do it like this:

class VendorItem < ActiveRecord::Base
  has_many :costs
end

class Cost < ActiveRecord::Base
  belongs_to :vendor_item
end


Then you can reference the fields through cost.vendor_item as you originally wanted. This is the Rails convention on how to do it.

Railscasts - Free Ruby on Rails Screencasts

Re: has_one vs. has_many

Yep, I'd like to do that but this is a legacy database that is used by many other applications so renaming columns isn't an option.

So I guess you just can't do a has_one with a "non-rails" key naming.

Re: has_one vs. has_many

since you have a key in both tables it sounds like you should be using belongs_to instead of has_one

class VendorItem < ActiveRecord::Base
   belongs_to :costs, :foreign_key => "itemid"
end
 
class Cost < ActiveRecord::Base
   belongs_to :vendor_item, :foreign_key => "vendoritemid"
end