ActiveRecord double belongs_to不包含外部关系

时间:2015-10-30 13:53:42

标签: ruby-on-rails activerecord model

在Rails 3.2中,我有一个带有单词和引用的字典,名为“gotowords”,用于存储它们所属的单词word_id以及它们在reference_id中引用的单词(即。{模型中的{1}}:

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

我不能(现在)重构像this answer那样建议,因为应用程序非常庞大并且会产生太多后果。也就是说,我可以使用补充查询,但它会让我感到烦恼......添加@words = Word.includes(:gotowords, :gotofroms) 并不能解决问题:

inverse_of

是否有解决方案在该配置中包含has_many :gotowords, inverse_of: :word has_many :gotofroms, class_name: "Gotoword", foreign_key: "reference_id", inverse_of: :gotofrom 两次?

1 个答案:

答案 0 :(得分:0)

尝试使用preload。它有点不同,但可能仍然有助于消除重复的数据库查询:

@words = Word.preload(:gotowords, :gotofroms)