如何在Rails中最好地实现查找表

时间:2015-04-12 14:08:43

标签: ruby-on-rails ruby

如何设置Rails以执行以下操作:

我有一个模特类贸易:

symbol of type String
price of type Float
currency of type String
date of type Date

然后我有一个查找表CrossRates

curr_a of type String
curr_b of type String
date of type Date
rate of type Float

表CrossRates有很多行,如下例所示:

EUR USD 2015-03-03 1.3593

假设我有一份交易报告,我想在交易日使用正确的CrossRate。假设交易是以货币USD进行的,我希望以欧元报告。

我应该如何设置模型之间的关系?

我是否必须手动阅读每笔交易的交叉汇率?我想避免使用自定义SQL(使用@result = ActiveRecord :: Base.connection.execute(sql)执行),因为我希望将报表中的行表示为:

trade.price * xrate

但我不确定如何获得“xrate”。我可以用哈希预加载整个表,然后用

查找
crossrates["EUR"]["USD"]["2015-03-03].rate 

但这似乎是一个尴尬的解决方案......

编辑:

这个查询做了我想要的,但它并不完全是“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)

如何使用模型来表达上述内容?

我认为下面这个问题的接受答案接近我想要的,但我不明白更精细的细节......

Advanced SQL in Rails

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

然后你可以这样打电话:

@users = User.who_knows("Joe", "Jack")

1 个答案:

答案 0 :(得分:0)

一种方法是不加入这两个表,将它们视为单独的模型。

在交易模型中,您拥有交易的currency和所需的cross_rate

在您的交易模型中,包括以下方法。

def get_cross_rate_report_for cross_rate
  xrate = CrossRate.where("curr_a == ? and curr_b == ?", currency, cross_rate).first().rate
  r = trade.price * xrate
  # add pretty print code here
end

请注意,我还没有对此进行测试,关键是where条件,它允许您按两列过滤结果并返回CrossRate模型,然后您可以在其上请求速率。请参阅here

为了加快查找速度,我会将索引添加到CrossRate表中。查看here以获取指导和示例代码(ctrl-f和搜索&#39;索引&#39;)。

相关问题