【问题标题】:Rails 3.0 associated model with download 'save to' image带有下载“保存到”图像的 Rails 3.0 关联模型
【发布时间】:2012-12-19 06:20:01
【问题描述】:

我的 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

带有friendlyid的壁纸模型:

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})

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    这是我得到它的方法
    路线

    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)
    “下载”将是视图“下载路径”中使用的路径的名称
    在这条路径中,我必须传递外键和 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 在生产中失败,请将其更改为 send_data 或
    在 config/production.rb 中注释掉这一行

    config.action_dispatch.x_sendfile_header = "X-Sendfile"  
    

    send_file just sends an empty file

    【讨论】:

      猜你喜欢
      • 2015-06-21
      • 2013-02-08
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多