Paperclip - 如何访问已保存的文件

时间:2014-10-28 16:02:10

标签: ruby-on-rails paperclip

每个人!我正在使用Paperclip上传文件

class Model
  include Mongoid::Document
  include Mongoid::Paperclip

  has_many :myfiles
 end

class Myfile
  include Mongoid::Document
  include Mongoid::Paperclip

  belongs_to :model 
  has_mongoid_attached_file :file,
   :path => ":rails_root/public/uploads/:class/:id/:basename.:extension",
 end

我的问题是如何在保存后访问上传的文件?我试过了:

    @model.myfiles.first.path
 @model.myfiles.first.url

它给出错误:

NoMethodError: undefined method `path' for #<Myfile:0x007fd22b336f80>

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

尝试:)

@model.myfiles.first.file.path
@model.myfiles.first.file.url

如果想要

,您可以委派这些字段
class Myfile
  include Mongoid::Document
  include Mongoid::Paperclip

  belongs_to :model 
  has_mongoid_attached_file :file,
   :path => ":rails_root/public/uploads/:class/:id/:basename.:extension"

  delegate :url, :path, to: :file, allow_nil: true, prefix: false
 end

然后你可以使用

@model.myfiles.first.path
@model.myfiles.first.url