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.
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.