【问题标题】:Rails ActiveRecord associations caching questionsRails ActiveRecord 关联缓存问题
【发布时间】:2015-03-26 13:36:11
【问题描述】:

在 Rails 中,当有 ActiveRecord 关联时,说:

class Song < ActiveRecord::Base
  has_many :artists_songs, :class_name => "ArtistSong"
  has_many :artists, :class_name => "Artist", :through => :artists_songs
end
class Artist< ActiveRecord::Base
  has_many :artists_songs, :class_name => "ArtistSong"
  has_many :songs, :class_name => "Song", :through => :artists_songs
end
class ArtistSong < ActiveRecord::Base
  belongs_to :song, :class_name => "Song"
  belongs_to :artist, :class_name => "Artist"
end

并说我访问了这样的歌曲

my_song = Song.joins(:artists).first
  1. 为什么我第一次访问艺人协会时会这样

    my_song.artists

    执行了一个新的 SQL 查询,尽管“joins”命令已经加载了艺术家列表?

  2. 在首次加载艺术家关联后(以便构建缓存),有没有办法过滤艺术家无需再次加载? 因为

    my_song.artists.where(Id: 55)

    每次执行时都会执行一个新查询,即使有可用的缓存。

谢谢。

【问题讨论】:

    标签: ruby-on-rails caching activerecord


    【解决方案1】:

    :joins 根本不加载关联 - 那是 :includes(及其变体 :preload:eager_load

    当您有关联时,使用关系方法(即从活动记录查询界面:whereincludesorder)将始终返回新关系(因此在使用时会触发新查询) .如果要使用加载的关联,请使用detect等数组方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      相关资源
      最近更新 更多