ruby-on-rails-3 – 如何创建一个rails应用程序,通过独特的自动
我有一个文件,我想提供在线下载,但仅限于选定的用户.
这是我想到的典型场景
我会使用rails来做这件事.我正在寻找的答案: >生成下载的唯一链接的正确方法是什么? 解决方法
首先,您需要设置一个用于存储令牌的模型:
rails g model DownloadToken token:string expires_at:timestamp download_token.rb class DownloadToken < ActiveRecord::Base attr_accessible :token,:expires_at before_create :generate_token def generate_token self.token = SecureRandom.base64(15).tr('+/=lIO0','abc123') end end 接下来,设置控制器来处理提交的表单(或更改现有操作)并生成令牌,发送电子邮件等. class FooController < ApplicationController def create #process submitted form ... #create a token that expires in 24 hours @token = DownloadToken.create(:expires_at => Time.now + 24.hours) #send email and redirect.. end end 您需要确保邮件程序视图包含以下内容: <%= link_to "Click Me","/files/downloads?token=#{@token.token}" %> 您还需要设置一个负责提供下载的控制器,它应该如下所示: class FileController < ApplicationController before_filter :check_token def check_token redirect_to :back,:flash => {:error => "Bad link"} if DownloadToken.where("token = ? and expires_at > ?",params[:token],Time.now).nil? end def download send_file '/home/your_app/downloads/yourfile.zip',:type=>"application/zip",:x_sendfile=>true end end routes.rb(假设Foo已经设置为RESTful资源) match 'files/download' => 'files#download' 此代码未经测试,但它应涵盖您需要的大部分内容,并让您了解您想要采取的方向. 补充阅读: > SecureRandom (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |