Ruby on rails 多个属于同一个表
我有两张桌子: 货币和汇率Ruby on rails 多个属于同一个表,ruby-on-rails,ruby-on-rails-3,model-associations,Ruby On Rails,Ruby On Rails 3,Model Associations,我有两张桌子: 货币和汇率 currencies: id:int, code:string, name: string rates: id:int, top_currency_id:int, bottom_currency_id:int, rate:float 我有两个关于它们的活动记录: class Rate < ActiveRecord::Base attr_accessible :bottom_currency, :rate, :top_currency, :top_curr
currencies: id:int, code:string, name: string
rates: id:int, top_currency_id:int, bottom_currency_id:int, rate:float
我有两个关于它们的活动记录:
class Rate < ActiveRecord::Base
attr_accessible :bottom_currency, :rate, :top_currency, :top_currency_id
belongs_to :top_currency, :class_name => 'Currency', :foreign_key => 'top_currency_id'
belongs_to :bottom_currency, :class_name => 'Currency', :foreign_key => 'bottom_currency_id'
end
class Currency < ActiveRecord::Base
attr_accessible :code, :name
has_many :rates
end
为什么Rails的魔力不起作用
非常感谢。据我所知,您的代码在理论上应该可以工作。但我确实认为你有点多余 这样做就足够了:
class Rate < ActiveRecord::Base
belongs_to :top_currency, class_name: 'Currency'
belongs_to :bottom_currency, class_name: 'Currency'
end
class Rate
Rails将推断
top\u currency
的外键为top\u currency\u id
,而bottom\u currency\u id
的外键为bottom\u currency
在您的两个属于的方法中,将外键
选项更改为主键
,其他一切保持原样
belongs_to :top_currency, :class_name => 'Currency', :primary_key => 'top_currency_id'
# ...
默认情况下,关联对象的主键是id
。但是,您的货币模型有三个主键,预期的id
加上两个额外的键:top\u currency\u id
和bottom\u currency\u id
。活动记录需要知道要查找哪个键。用主键告诉它
选项
当外键不同于关联的名称(属于:name
)加上“\u id
”时,需要使用外键
选项。由于外键与关联名称加上“\u id
”匹配,因此不需要使用外键
选项 我认为你不能这样质疑这种关系。要使用您的示例:
top_currency = Currency.find_by_id(1)
@test = Rate.where(:top_currency=>top_currency)
您必须将其更改为:
top_currency = Currency.find_by_id(1)
@test = Rate.where(:top_currency_id => top_currency.id)
但这样做可能更容易:
top_currency = Currency.find_by_id(1)
@test = top_currency.rates
错误表明top\u currency
不是rates
表中的一列,您确定已将更改迁移到您使用的环境中吗?@jaredmater我有top\u currency\u id列,我认为Rails应该查找top\u currency\u id列而不是top\u currency。是的,@test=Rate.where(:top\u currency\u id=>top\u currency.id)
甚至@test=Rate.where(:top\u currency\u id=>top\u currency)
工作得很好。但是我想让Rate.where(:top\u currency=>top\u currency)
工作得很好,我很好奇为什么你会如此执着于Rate.where(:top\u currency=>top\u currency)
当您设置的关联为您提供方法top\u currency.rates
来做同样的事情时?@MollyStruve实际上我需要执行以下请求:Rate.where(:top\u currency=>top\u currency,:bottom\u currency=>bottom\u currency)
据我所知,你不能这样做。向每个符号添加id,它就会起作用。我知道你想要什么,但在一个简单的查询中是不可能的。你正在寻找一个连接,这比简单地检查相关记录的id要昂贵得多。不,不幸的是,我只有一个主键。你确定类name不应该是符号或字符串?
top_currency = Currency.find_by_id(1)
@test = top_currency.rates