Associations Not Based off ID

I'm trying to create an association that is not based off a table's ID
column.

For example,

Product
ID (int)
SKU (string)

Inventory
ID (int)
SKU (string)

I want to be able to create the association using the SKU column, so
that if a i have a product with SKU 'abc', I could call
product.inventory and get the inventory with SKU 'abc'. Is this
possible? I know there is a foreign_key attribute in associations, but
that doesn't solve the whole issue since it ends up comparing ID vs SKU,
not SKU vs SKU.

Thanks for your help!

Cheers!

Add a custom finder that searches by self.sku.

def by_sku
  Inventory.find_by_sku( self.sku )
end

Raymond, I think you are mixing concerns here.

Concern #1 is finding the correct product by sku
Concern #2 is finding the inventory for a product (which, in this
case, you've identified by sku).

You could then have something along the lines of what Greg suggests:

@product = Product.find_by_sku some_sku
@inventory = @product.inventory

Note that you can also get the inventory based on sku directly using
includes and conditions properly:

class Inventory < ARec::Base
  belongs_to :product

  def self.find_by_sku(sku)
    self.find(:all/
first, :include=>:product, :conditions=>['products.sku = ?', sku])
  end
end

@inventory = Inventory.find_by_sku some_sku

I think you'll be much better off in the long run using the ID field
for your associations. In this particular case sku will be come
redundant information kept in various places in your system and will
invariably lead to broken data when "the powers that be" decide to
implement a new strategy for assigning skus.

HTH,
AndyV