Rails ActiveRecord关联缓存问题

时间:2015-01-27 20:00:25

标签: ruby-on-rails caching activerecord

在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查询,尽管艺术家列表已经被&#34;加入&#34;命令?

  2. 首次加载艺术家协会(以便构建缓存)后,有没有办法过滤艺术家而不再加载? 因为

    my_song.artists.where(Id:55)

    只要有可用的缓存,

    每次执行时都会执行

  3. 感谢。

1 个答案:

答案 0 :(得分:1)

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

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