My Rails 3.0.3应用程序有一个脚手架'月',其中有一个链接,用户可以使用'保存到'来下载图像。 现在我需要建立一个月份模型属于壁纸模型的关联。
路线:
root :to => 'inicio#index'
resources :wallpapers do
resources :months
end
# the route that works with no association
# match 'download/:id' => 'months#download', :as => :download
# the route I tried
match 'wallpapers/:id/months/:id' => 'months#download', :as => :download
月份模型:
class Month < ActiveRecord::Base
belongs_to :wallpaper
has_attached_file :wallpaper_picture, :styles => {
:default => { :geometry => '530x330', :quality => 80, :format => 'jpg'}
}
end
有友好的壁纸模型:
class Wallpaper < ActiveRecord::Base
has_many :months, :dependent => :destroy
extend FriendlyId
friendly_id :title, :use => :slugged
end
在months_controller中我制作了下载方法,此方法无需关联:
class MonthsController < InheritedResources::Base
belongs_to :wallpaper, :finder => :find_by_slug!
def download
@wallpaper = Wallpaper.find(params[:wallpaper_id])
@month = @wallpaper.month.find(params[:id])
send_file @month.wallpaper_picture.path,
:filename => @month.wallpaper_picture_file_name,
:type => @month.wallpaper_picture_content_type,
:disposition => 'attachment'
end
end
查看月/索引
- @months.each do |month|
= link_to image_tag(month.wallpaper_picture(:default)), wallpaper_month_path(month.wallpaper, month)
我尝试在months_controller中更改下载方法,但这是错误的:
@months = Wallpaper.month.conditions({:person_id => some_id})
答案 0 :(得分:0)
以下是我如何得到它 路线
resources :wallpapers do
resources :months
end
match 'wallpaper/:wallpaper_id/download/:id' => 'months#download', :as => :download
在路线中我必须通过:wallpaper_id(has_many:months),
:id是当前控制器的id(belongs_to:wallpaper)
'download'将是视图'download_path'中使用的路径的名称
在这条路径中,我必须传递外键和id
查看月/索引
- @months.each do |month|
= link_to 'Download Picture', download_path(month.wallpaper_id, month.id)
在months_controller 中,下载方法将接收这些参数并将相关图像传递给send_file方法。
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
PD:如果send_file在Production中失败,请将其更改为send_data或
在config / production.rb中注释掉这一行
config.action_dispatch.x_sendfile_header = "X-Sendfile"