加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 多个belongs_to到同一个表

发布时间:2020-12-17 03:36:43 所属栏目:百科 来源:网络整理
导读:我有两张桌子: 货币和利率 currencies: id:int,code:string,name: stringrates: id:int,top_currency_id:int,bottom_currency_id:int,rate:float 我有两个活跃的记录: class Rate ActiveRecord::Base attr_accessible :bottom_currency,:rate,:top_currenc
我有两张桌子:

货币和利率

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,:foreign_key => 'bottom_currency_id'
end


class Currency < ActiveRecord::Base
  attr_accessible :code,:name

  has_many :rates
end

所以问题是:
当我想执行以下代码时:
????top_currency = Currency.find_by_id(1)
????@test = Rate.where(:top_currency => top_currency)

我收到以下错误:

Mysql2::Error: Unknown column 'rates.top_currency' in 
'where clause': SELECT `rates`.* FROM `rates`  WHERE `rates`.`top_currency` = 1

为什么Rails的魔法不起作用?

非常感谢.

解决方法

在您的两个belongs_to方法中,将foreign_key选项更改为primary_key,将其他所有内容保留为原样.

belongs_to :top_currency,:primary_key => 'top_currency_id'
# ...

默认情况下,关联对象的主键是id.但是,您的货币模型有三个主键,预期ID加上两个额外的键:top_currency_id和bottom_currency_id. Active Record需要知道要查找的密钥.使用primary_key选项告诉它.

当外键不同于关联的名称(belongs_to:name)加上“_id”时,需要foreign_key选项.由于您的外键与关联名称加上“_id”匹配,因此您不需要使用foreign_key选项.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读