CarrierWave和多个上传器,可根据特定型号的永久链接存储文件

时间:2012-10-10 16:54:26

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 carrierwave

有人可以帮助了解CarriveWave的store_dir。

如何根据相关的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

道歉,如果我想要这么清楚,但要非常感谢所给予的任何见解。

1 个答案:

答案 0 :(得分:2)

可能最简单的方法是将永久链接委托给模型上的父级

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

  mount_uploader :car_image, CarUploader



end