我使用Carrierwave在我的Rails 4应用中上传图片。例如,用户可以上传头像。到目前为止一切正常,我可以通过附加" _url"来生成我视图中的头像图像。使用
到文件字段 @users.each do |user|
user.avatar_url(:small)
end
但是,有时候我没有User对象可用,例如我刚加入时就像这样:
@listings = Listing.joins(:user).select("listings.*, user.avatar as avatar")
#I know I could use :includes, but this isn't always practical in my app
因此,我无法自动生成路径,并且必须依赖于在我的视图中手动创建路径,如下所示:
<% if Rails.env.production? %>
<%= image_tag("https://fullpath.com/uploads/user/avatar/#{listing.user_id}/small_#{listing.p_user_avatar}") %>
<% else %>
<%= image_tag("https://fullpath.com/uploads/user/avatar/#{listing.user_id}/small_#{listing.p_user_avatar}") %>
<% end %>
另一个选择是写一个帮助器来生成这些URL,所以至少他们在一个地方。但Carrierwave肯定有内置的处理方式吗?我应该怎么做呢?
class User < ActiveRecord::Base
mount_uploader :avatar, UserAvatarUploader
end
class UserAvatarUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :small do
process :resize_to_fill => [100, 100]
process :quality => 75
end
def extension_white_list
%w(jpg jpeg gif png)
end
end