【发布时间】:2015-10-30 13:53:41
【问题描述】:
在 Rails 3.2 中,我有一个包含单词和引用的字典,名为“gotowords”,其中存储了它们在 word_id 中所属的单词以及它们在 reference_id 中引用的单词(即 gotofrom 在模型):
create_table "words", :force => true do |t|
t.string "word"
t.text "definition"
end
create_table "gotowords", :force => true do |t|
t.integer "word_id"
t.integer "reference_id"
end
与模型:
class Word < ActiveRecord::Base
has_many :gotowords
has_many :gotofroms, class_name: "Gotoword", foreign_key: "reference_id"
end
class Gotoword < ActiveRecord::Base
belongs_to :word
belongs_to :gotofrom, class_name: "Word", foreign_key: "id"
end
以下查询有效,但对显然不包括在内的每个 gotofroms.word 进行另一个查询:
@words = Word.includes(:gotowords, :gotofroms)
我(目前)不能像this answer 建议的那样重构,因为应用程序非常庞大并且会产生太多后果。也就是说,我可以接受补充查询,但它让我很烦恼......按原样添加inverse_of 并不能解决问题:
has_many :gotowords, inverse_of: :word
has_many :gotofroms, class_name: "Gotoword", foreign_key: "reference_id", inverse_of: :gotofrom
是否有解决方案在该配置中包含两次 Word?
【问题讨论】:
标签: ruby-on-rails activerecord model