开发者

rails find model without loading relevant associations

开发者 https://www.devze.com 2023-02-01 01:19 出处:网络
My rails application has two models, gallery and photo.Galleries have many photos and photos belong to one gallery.

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 开发者_如何学Pythonthe 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消