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
为什么我第一次访问艺术家协会时
my_song.artists
执行新的SQL查询,尽管艺术家列表已经被&#34;加入&#34;命令?
首次加载艺术家协会(以便构建缓存)后,有没有办法过滤艺术家而不再加载? 因为
my_song.artists.where(Id:55)
只要有可用的缓存,每次执行时都会执行 。
感谢。
答案 0 :(得分:1)
:joins
根本不加载关联 - :includes
(及其变体:preload
和:eager_load
当你有一个关联时,使用关系方法(即来自活动记录查询界面:where
,includes
,order
)将始终返回一个新关系(因此将触发使用时的新查询)。如果要使用已加载的关联,请使用detect
等数组方法。