这是我在关联模型中使用的默认代码,用于从 Paperclip 下载图像作为 save_to。
月控制器
def download
@wallpaper = Wallpaper.find(params[:wallpaper_id])
@month = @wallpaper.months.find(params[:id])
send_file @month.wallpaper_picture.path,
:filename => @month.wallpaper_picture_file_name,
:type => @month.wallpaper_picture_content_type,
:disposition => 'attachment'
end
路线
resources :wallpapers do
resources :months
end
match 'wallpaper/:wallpaper_id/download/:id' => 'months#download', :as => :download
查看/月/索引
- @months.each do |month|
= link_to 'default', download_path(month.wallpaper_id, month.id)
但是我的应用程序在我的模型中声明了近 6 种不同样式的回形针,并且每种样式都必须是可下载的。为此,我这样做了(我将仅显示 6 个代码块中的 2 个):
月控制器
def download_iphone4
@wallpaper = Wallpaper.find(params[:wallpaper_id])
@month = @wallpaper.months.find(params[:id])
@month = 'public/system/wallpaper_pictures/' + @month.id.to_s + '/iphone4/' + @month.wallpaper_picture_file_name
send_file @month,
:disposition => 'attachment'
end
def download_iphone5
@wallpaper = Wallpaper.find(params[:wallpaper_id])
@month = @wallpaper.months.find(params[:id])
@month = 'public/system/wallpaper_pictures/' + @month.id.to_s + '/iphone5/' + @month.wallpaper_picture_file_name
send_file @month,
:disposition => 'attachment'
end
def download_ipad ...
def download_1440 ...
def download_1680 ...
def download_1920 ...
etc ...
路线
match 'wallpaper_pictures/:wallpaper_id/iphone4/:id' => 'months#download_iphone4', :as => :download_iphone4
match 'wallpaper_pictures/:wallpaper_id/iphone5/:id' => 'months#download_iphone5', :as => :download_iphone5
match 'wallpaper_pictures/:wallpaper_id/ipad4/:id' => 'months#download_ipad', :as => :download_ipad
match 'wallpaper_pictures/:wallpaper_id/1440/:id' => 'months#download_1440', :as => :download_1440
match 'wallpaper_pictures/:wallpaper_id/1680/:id' => 'months#download_1680', :as => :download_1680
match 'wallpaper_pictures/:wallpaper_id/1920/:id' => 'months#download_1920', :as => :download_1920
观看次数/月/索引
- @months.each do |month|
= link_to 'iphone4', download_iphone4_path(month.wallpaper_id, month.id)
= link_to 'iphone5', download_iphone5_path(month.wallpaper_id, month.id)
= link_to 'ipad', download_ipad_path(month.wallpaper_id, month.id)
= link_to '1440', download_1440_path(month.wallpaper_id, month.id)
= link_to '1680', download_1680_path(month.wallpaper_id, month.id)
= link_to '1920', download_1920_path(month.wallpaper_id, month.id)
我的问题来了:
1)我可以用更清洁/更好的方式来做吗?
2)我必须将块从我的控制器移动到模型或新控制器吗?
3)在代码的第一个和默认方法中,有一些哈希值,例如:
:filename => @month.wallpaper_picture_file_name,
:type => @month.wallpaper_picture_content_type
但在另一种方法中,我意识到我不需要使用它们。这些哈希是必要的吗?
4)我称它们为“哈希器”。这是正确的吗?还有什么更正吗?
PD:如果 send_file 在 Production 中失败,将其更改为 send_data 或
在 config/production.rb 中注释掉这一行
config.action_dispatch.x_sendfile_header = "X-Sendfile"