Rails 查找模型而不加载相关关联
我的 Rails 应用程序有两个模型,画廊和照片。画廊有很多照片,照片属于一个画廊。
当我删除照片时,我注意到 Rails 还加载了图库 - 这是我不需要的。这是一个添加的数据库查询。
当我找到
要删除的照片时,我使用@photo = Photo.find(params[:id])
。这会加载关联。
我知道有 @photo = Photo.find(params[:id], :include => :gallery)
,它告诉它加载图库。与此相反的是什么?我尝试了以下操作:
@photo = Photo.find(params[:id], :include => [])
@photo = Photo.find(params[:id], :include => nil)
我还尝试仅选择删除照片所需的字段,但我需要 gallery_id
才能删除实际文件,因为文件的路径是基于离开画廊。这最终也会加载图库。
编辑: 我的 Photo
模型如下所示:
class Photo < ActiveRecord::Base
belongs_to :gallery
mount_uploader :file, PhotoUploader
end
mount_uploader
来自 carrierwave。我有一个上传器,其中包含以下代码:
def store_dir_base
"galleries/#{model.gallery.id}/"
end
它是罪魁祸首吗?
谢谢!
My rails application has two models, gallery and photo. 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])
. This loads the association.
I know that there is @photo = Photo.find(params[:id], :include => :gallery)
, which tells it to load the 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. This just ends up loading the gallery too.
Edit:
My Photo
model looks like this:
class Photo < ActiveRecord::Base
belongs_to :gallery
mount_uploader :file, PhotoUploader
end
mount_uploader
is from 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况的原因是我用于载波的
uploader
代码。这段代码正在访问图库模型,而我需要访问的只是 id:
我所要做的就是将其更改为:
这样我就可以访问
photo
模型列gallery_id
而不是gallery
模型。The reason this was happening was because of my
uploader
code that I used for carrierwave.This code was accessing the gallery model, when all I needed to access was the id:
All I had to do was change it to:
This made it so I was accessing the
photo
model columngallery_id
instead of thegallery
model.