[英]rails find model without loading relevant associations
My rails application has two models, gallery and photo. 我的Rails应用程序有两个模型,画廊和照片。 Galleries have many photos and photos belong to one gallery. 画廊有很多照片,而照片属于一个画廊。
When I delete a photo, I noticed that rails also loads the gallery - which I do not need. 删除照片时,我注意到护栏也加载了画廊,这是我不需要的。 It is an added database query. 这是一个添加的数据库查询。
When I find
the photo to delete, I use @photo = Photo.find(params[:id])
. 当我find
要删除的照片时,我使用@photo = Photo.find(params[:id])
。 This loads the association. 这将加载关联。
I know that there is @photo = Photo.find(params[:id], :include => :gallery)
, which tells it to load the gallery. 我知道有@photo = Photo.find(params[:id], :include => :gallery)
,它告诉它加载图库。 What is the opposite of this? 这是什么相反? I tried the following: 我尝试了以下方法:
@photo = Photo.find(params[:id], :include => [])
@photo = Photo.find(params[:id], :include => nil)
I also tried to select only the fields that I need in order to delete the photo, but I need the gallery_id
in order to delete the actual file because the path of the file is based off the gallery. 我还尝试只选择删除照片所需的字段,但是为了删除实际文件,我需要gallery_id
,因为文件的路径基于图库。 This just ends up loading the gallery too. 最终也只是加载图库。
Edit: My Photo
model looks like this: 编辑:我的Photo
模型如下所示:
class Photo < ActiveRecord::Base
belongs_to :gallery
mount_uploader :file, PhotoUploader
end
mount_uploader
is from carrierwave . mount_uploader
来自carrierwave 。 I have an uploader with the following code in it: 我有一个包含以下代码的上传器:
def store_dir_base
"galleries/#{model.gallery.id}/"
end
Could it be the culprit? 可能是罪魁祸首吗?
Thanks! 谢谢!
The reason this was happening was because of my uploader
code that I used for carrierwave. 发生这种情况的原因是因为我使用了用于载波的uploader
代码。
This code was accessing the gallery model, when all I needed to access was the id: 当我需要访问的是id时,这段代码正在访问画廊模型:
def store_dir_base
"galleries/#{model.gallery.id}/"
end
All I had to do was change it to: 我要做的就是将其更改为:
def store_dir_base
"galleries/#{model.gallery_id}/"
end
This made it so I was accessing the photo
model column gallery_id
instead of the gallery
model. 做到这一点,所以我要访问photo
模型列gallery_id
而不是gallery
模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.