【问题标题】:Ruby on Rails: Using Foreign Key twice in the same table?Ruby on Rails:在同一张表中使用两次外键?
【发布时间】:2016-12-18 21:23:33
【问题描述】:

我有两个模型:

class Word < ApplicationRecord
  has_many :g_words, class_name: 'Translation', foreign_key: 'g_id'
  has_many :v_words, class_name: 'Translation', foreign_key: 'v_id'
end

class Translation < ApplicationRecord
  belongs_to :g, class_name: 'Word', required: true
  belongs_to :v, class_name: 'Word', required: true
end

表格翻译

t.text "note", limit: 65535
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer  "g_id"
t.integer  "v_id"

Words 表中我已经插入了 2 个值:

id     body
1      Home
2      Maison

当我创建一个新的翻译时

g_id     v_id
1        2

然后出现以下错误。

在互联网上搜索了很多关于我的问题的帖子,这里有一篇关于我想要实现的目标的帖子:http://www.emreakkas.com/ruby-on-rails/rails-multiple-columns-to-the-same-tables-key

我尝试实施但失败了。

我不知道是我实现了错误的关联还是我声明了错误的外键。我真的不知道从哪里开始查找错误。我希望你能帮帮我!谢谢!

【问题讨论】:

  • 欢迎来到stackoverflow。请不要对 Ruby 或任意代码使用 sn-ps 功能。它用于创建可运行的 JS/CSS/HTML 示例。此外,您应该将错误消息的相关部分作为文本包含在问题正文中作为文本。通过编辑答案而不是评论来回应。

标签: mysql ruby-on-rails ruby foreign-keys


【解决方案1】:

如果您正在寻找构建翻译表,您可以这样做:

class Word < ApplicationRecord
  has_many :translations
  has_many :languages, through: :translations
end

class Language < ApplicationRecord
  has_many :translations
  has_many :words, through: :translations
end

class Translation < ApplicationRecord
  belongs_to :language
  belongs_to :word
end

但是 Rails 已经有 a built in i18n API 处理翻译,在重新发明轮子之前你应该先看看。

【讨论】:

  • 您好,谢谢您的回答。但我认为你错了。我想在 TRANSLATIONS 表中使用两次表 WORDS 中的相同外文。
  • *外键@max
  • 你的整个数据库设计是倒退的。使用相同的密钥无法解决问题。
  • 这正是我想要实现的目标:emreakkas.com/ruby-on-rails/…
  • @stackoverflow.com/users/544825/max 请你再看看。谢谢
猜你喜欢
  • 2011-07-12
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多