0

有人可以協助CarriveWave的store_dir。CarrierWave和多個上傳者根據特定模型的固定鏈接來存儲文件

如何有多個圖像模型存儲基於關聯的belongs_to模型的永久鏈接文件?

# Garage model 
class Garage < ActiveRecord:Base 

    attr_accessible: :avatar, :permalink, :car_image_attributes, 
        :motorcycle_image_attributes 

    has_many :car_image 
    has_many :motorcycle_image 

    mount_uploader :avatar, AvatarUploader 

    def set_permalink 
    self.permalink = permalink.parameterize 
    end 

    def to_param 
    permalink.parameterize 
    end 

end 

這就是我的圖像模型與CarrierWave

# Car Image model 
CarImage < ActiveRecord:Base 
    belongs_to :garage 
    attr_accessible: :garage_id, :image 

    mount_uploader :car_image, CarUploader 

end 

# Motocycle Image model 
MotocycleImage < ActiveRecord:Base 
    belongs_to :garage 
    attr_accessible: :garage_id, :image 

    mount_uploader :motorcycle_image, MotocycleUploader 

end 

這是我的CarrierWave上傳樣子鏈接。

# CarrierWave avatar uploader 
avatar_uploader.rb 
    # This uploader directly relates to the Garage model table 
    # column avatar:string. 

    def store_dir 
    # This works for the avatar because it calls on the Garage permalink 
    # but it fails for the other image models because it's a model relation 
    # has_many, belongs_to and the model.permalink will be based on the 
    # uploader's respective model and not the Garage model 
    # eg. car_uploader.rb = model.permalink = CarImage.permalink 
    # I would like it to refer to to Garage.permalink at all times. 
    "garage/#{model.permalink}/#{mounted_as}/" 
    end 
end 

# CarrierWave car and motorcycle uploaders 
car_uploader.rb 
# Fails to upload because it doesn't know what permalink is 
end 

motorcycle_uploader.rb 
# Fails to upload because it doesn't know what permalink is 
end 

道歉,如果我想清楚,但非常感謝任何洞察力。

回答

2

可能是最簡單的方法是將委託永久於母公司的模型

CarImage < ActiveRecord:Base 
    belongs_to :garage 
    delegate : permalink, :to => :garage 
    attr_accessible: :garage_id, :image 

    mount_uploader :car_image, CarUploader 



end 
+0

謝謝尤里的幸福。感謝您向我公開委託類方法,以及ActiveRecord關聯的用處。 –

+0

很高興我能幫到你。請享用:) –

相關問題