我不确定这是否没有得到回答,但我不确定要搜索什么,所以如果我要问的问题已经得到回答,请指出正确的方向。
我有 2 个模型:
stock_symbol 和 weight_symbol
stock_symbol中包含与weight_symbol 模型symbol
匹配的内容commodity
我怎样才能让关联起作用,所以当我做 stock_symbol.weight_symbol 时,我会找回 weight_symbol。
我知道如何在 SQL 中做到这一点,但如果它不是标准id
,this_id
那么我大多迷失了。
编辑:
class StockSymbol < ActiveRecord::Base
has_many :weight_symbols, primary_key: :symbol
def commodity
"LC" # This is just an example to simplify it, there is much more to this.
end
end
class WeightSymbol < ActiveRecord::Base
belongs_to :stock_symbol, foreign_key: :commodity
end
来自 stock_symbol 的示例对象:
StockSymbol.last
<#StockSymbol id: 729, symbol: "LCJ13C12500", created_at: "2013-03-15 21:50:49", updated_at: "2013-03-15 21:50:49">
来自 weight_symbol 的示例对象:
WeightSymbol.first
<#WeightSymbol id:1, weight_group_id: 1, symbol: "LC", created_at: "2010-01-05 21:13:28", updated_at: "2010-01-05 21:13:28">
设置并运行后,StockSymbol.last.weight_symbols.to_sql
我得到:
"SELECT `weight_symbols`.* FROM `weight_symbols` WHERE `weight_symbols`.`stock_symbol_id` = 'LCJ13C12500'"
编辑2:
查询它应该做什么(我认为):
SELECT * FROM `weight_symbols` WHERE `weight_symbols`.`symbol` = 'LC';
查询以获取我想要的信息。
SELECT * FROM `weight_symbols` a
JOIN `stock_symbols` b
ON a.symbol = b.commodity
WHERE b.symbol = 'LCJ13C12500';
新的股票代码对象
<#StockSymbol id: 729, symbol: "LCJ13C12500", created_at: "2013-03-15 21:50:49", updated_at: "2013-03-15 21:50:49", commodity: "LC">