user1854802
user1854802

Reputation: 388

Creating new table - how to set up table with two columns linking to same column in another table?

The application has an existing table exchanges and currencies. such that

select id, name, currency_id from exchanges;

 id | name | currency_id
----+------+-------------
  1 | ASX  | 1      (Australian Stock Exchange)
  3 | LSE  | 3      (London Stock Exchange)
  4 | NYSE | 2      (New York Stock Exchange)
  2 | AMEX | 2  

and

select id, name from currencies;

 id | name 
----+------
  1 | AUD     (Australian Dollar)
  2 | USD     (U.S. Dollar)
  3 | GBP     (Great Britain Pound)

Now I wish to allow users with a given base_currency of say AUD ( e.g @user.currency_id == 1 ) to be able to do currency conversions. Initially I thought of a table along these lines

exchange_rate table:
base_currency (currency_id), target_currency (currency_id), exchange_rate

e.g. could have values of conversion of AUD to USD where you multiply the AUD amount by 0.8235

1, 2, 0.8235  

If I try and create the table exchange_rates with two columns called currency_id the migration fails. If I use another name for one of the two currency columns I get compile errors when I try to display the currency name e.g @exchange_rate.base_currency.currency.name gives an error whereas @exchange_rate.currency.name gives AUD/USD/GBP.

Currently the exchange_rate table is as follows

table "exchange_rates", force: true do |t|
  t.integer  "base_currency"
  t.integer  "currency_id"
  t.float    "exchange_rate"
  t.datetime "created_at"
  t.datetime "updated_at"
end

Do I change the database names for exchange_rate table or how do I reference the exchange for base_currency.

Upvotes: 1

Views: 83

Answers (1)

Abubakar
Abubakar

Reputation: 1032

In your ExchangeRate Model define association using foreign key

has_one :base_currency,   foreign_key: 'base_currency', class_name: 'Currency'
has_one :currency

now your can access both your currency and base currency like this

@exchange_rate.base_currency.name
@exchange_rate.currency.name

Upvotes: 1

Related Questions