Rails 查找模型而不加载相关关联

发布于 2024-10-09 09:42:17 字数 962 浏览 0 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

零崎曲识 2024-10-16 09:42:17

发生这种情况的原因是我用于载波的 uploader 代码。

这段代码正在访问图库模型,而我需要访问的只是 id:

def store_dir_base
    "galleries/#{model.gallery.id}/"
end

我所要做的就是将其更改为:

def store_dir_base
    "galleries/#{model.gallery_id}/"
end

这样我就可以访问 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文