gpt4 book ai didi

mysql - ruby rails : Using Foreign Key twice in the same table?

转载 作者:行者123 更新时间:2023-11-28 23:22:04 25 4
gpt4 key购买 nike

我有两个模型:

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

然后出现如下错误。 enter image description here

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

我尝试实现但失败了。

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

最佳答案

如果你想建立一个翻译表,你会这样做:

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它处理翻译,您应该在重新发明轮子之前先看一下。

关于mysql - ruby rails : Using Foreign Key twice in the same table?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41144455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com