Zelid
Zelid

Reputation: 7195

ActiveRecord string primary key used in foreign keys

It's possible to override ActiveRecord's primary key to be a string, and have a custom type like:

create_table :system_currencies, :primary_key => 'iso_code' do |t|
      t.column :iso_code, :string, :limit => 3
end

But how to use this table/model in other models that have references to it? For references ActiveRecord always expects the foreign key column to end with "_id" and to be an integer value.

Is it true? How to do a reference to such SystemCurrency model from an Order model in the situation when SystemCurrency uses string iso_code as primary key?

Upvotes: 2

Views: 2520

Answers (1)

iHiD
iHiD

Reputation: 2438

You can specify the primary key on a join. For example:

class Order < ActiveRecord::Base
  belongs_to :system_currency, :primary_key => "iso_code"
end 

More information can be found in the Rails API at http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to

Is this what you are after or have I misunderstood your question?

Upvotes: 4

Related Questions