ActiveRecord 双向外键。
我在 MYSQL 中使用一些开放的政府数据,并将其导入到我的 Rails 应用程序中。
我已经用我自己的一些表扩展了数据库,并在我的表中使用了 Rails 提供的列 ID。
然而,原始数据库的表是通过唯一的“ndb”id 链接的。
我认为通过在模型之间交叉引用两个 :foreign_key=>'ndb'
我可以正确链接表格,但通过 :foreign_key
,它似乎是将一个表中的 id 链接到另一个表的 ndb 列。
我的模型看起来像这样
class Food < ActiveRecord::Base has_many :weights, :foreign_key=>'ndb' has_many :food_names end class Weight < ActiveRecord::Base belongs_to :food, :foreign_key=>'ndb'
有没有办法指定“ndb”列是食物和权重表之间的链接,而不是食物ID到ndb?
I'm using some open gov data in MYSQL which I've imported into my rails App.
I've extended the database with some of my own tables, and use the rails provided column ids in my tables.
However, the tables of the original database are linked through a unique 'ndb' id.
I thought that by cross-referencing two :foreign_key=>'ndb'
between the models I would get the tables linked properly, but through :foreign_key
, it appears to be linking the id from one table to the ndb column of another.
My models look like this
class Food < ActiveRecord::Base has_many :weights, :foreign_key=>'ndb' has_many :food_names end class Weight < ActiveRecord::Base belongs_to :food, :foreign_key=>'ndb'
Is there a way to specify that the 'ndb' column is the link between the food and weights table, and not the food_id to ndb?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否在 AR 课程中尝试过
set_primary_key 'ndb'
?set_primary_key 文档。
Have you tried
set_primary_key 'ndb'
in your AR classes?set_primary_key docs.
我所做的可能是临时解决方案是使用
:finder_sql
将表链接在一起。我的食物模型现在有:
我不确定这是否是最好的解决方案,但它似乎有效。
What I've done as a possibly temporary solution, is to used the
:finder_sql
to link the tables together.My Food model now has:
I'm not sure if this is the best solution or not, but it seems to be working.