【问题标题】:ActiveRecord double belongs_to doesn't include the foreign relationActiveRecord double belongs_to 不包括外部关系
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,看起来很有希望,但我仍然有重复的查询。
    • 多亏了你,我发现了eager_load,它的性能更好,但也不能解决重复查询。
    • 奇怪的是没有帮助。你能从你的日志中发布数据库查询吗?
    • preload(或includes)的数据库查询,然后是eager_load的查询:http://pastebin.com/0TtpRBKV
    • 这真的很奇怪。也许它与视图中的某些代码更相关?
    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 2013-09-24
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多