How would I setup Rails to do the following:
I have a model class Trade:
symbol of type String
price of type Float
currency of type String
date of type Date
I then have a lookup table CrossRates
curr_a of type String
curr_b of type String
date of type Date
rate of type Float
The table CrossRates have many rows like this example:
EUR USD 2015-03-03 1.3593
Let's say I have a report of trades, where I want to use the right CrossRate for the date of the trade. Assume that the Trade is made in currency USD, and I want the report in EUR.
How should I setup the relationships between the models?
Do I have to read in the Crossrate manually for each trade? I'd like to avoid custom SQL (executed with @result = ActiveRecord::Base.connection.execute(sql)) since I would prefer to express the rows in the report as:
trade.price * xrate
but I'm not sure how to get the "xrate". I can pre-load the whole table in a hash and look it up with
crossrates["EUR"]["USD"]["2015-03-03].rate
but it seems like an awkward solution....
EDIT:
This query does what I want, but it's not exactly "Railsy"...
SELECT
t.SYMBOL as 'symbol',
DATE(trade_time) as 'date',
price*-qty*p.contract_size,
p.currency,
cr.ratio
FROM
alpha.trades t, products p, crossrates cr
WHERE
t.symbol = p.symbol and t.dt = "2015-03-03" and cr.dt = "2015-03-03" and
cr.currency_a = p.currency and cr.currency_b = "SEK"
ORDER BY
SYMBOL, DATE(trade_time)
How can I express the above using Models instead?
I think the accepted answer on this question below is close to what I want, but I don't understand the finer details...
class User < AR
has_many :friends
def self.who_knows(*friend_names)
joins((1..friend_names.length).map{ |n|
"INNER JOIN friends AS f#{n} ON users.id = f#{n}.user_id AND f#{n}.name = ?" }.join(" "),
*friend_names)
})
end
end
Which you then can call like this:
@users = User.who_knows("Joe", "Jack")
cross_ratestable ?. Describe the flow in order to let you know whats best :) How are both tables associated if not then how are you keeping/storing/creating cross rates ?