2011-12-27 59 views
0

似乎有一些人已经得到了回形针定期Ruby类的工作做类似如下:如何在不从ActiveRecord :: Base继承的类中使用Paperclip gem for Rails?

require "paperclip" 

Class Person 
    include Paperclip 
    has_attached_file :avatar,{} 
end 

here 使用主回形针回购​​,即使这并不为我工作:

$ bundle exec rails c 
>> Rails.version 
=> "3.1.3" 
>> require 'paperclip' 
=> false 
>> class Monkey 
>> include Paperclip 
>> has_attached_file :avatar,{} 
>> end 
NoMethodError: undefined method `has_attached_file' for Monkey:Class 

有没有人得到这个工作,并可能提供一个线索可能会出错?

谢谢!

回答

2

Paperclip非常明确地用于AR。

另一种选择是使用载波,而不是它工作得很好AR的外侧,与各种运筹学和管理学的,或无:

https://github.com/jnicklas/carrierwave

+0

载波看起来非常好,但似乎人们已经拿到回形针以外的回形针。我可能会使用载波,无论如何避免将Paperclip的主要目标是AR的未来复杂化。 – Tony 2011-12-27 19:34:55

+0

我同意 - 所有的事情都是可能的,我相信它可以完成。我认为你可能会用回形针游泳,以便用于这种用途。 – 2011-12-28 03:50:47

0

我最近不得不想出解决办法。你需要使用一些ActiveModel的东西来定义你的库类或模型。具体来说,要使用Paperclip,需要以下方法:保存,销毁,回调,to_key(用于form_for),attr_acessors for id,当然还有每个附加文件的* _file_name,* _file_size,* _content_type,* _updated_at 。

下面的类应该给你你需要的最小实现。截至2012年9月10日,这个“解决方案”使用Rails 3.2.8,Ruby 1.9.3和Paperclip 3.2.0,但其他配置也可能起作用。

class Importer 
    extend ActiveModel::Callbacks 
    include ActiveModel::Validations 

    include Paperclip::Glue 

    define_model_callbacks :save 
    define_model_callbacks :destroy 

    validate :no_attachement_errors 

    attr_accessor :id, :import_file_file_name, :import_file_file_size, :import_file_content_type, :import_file_updated_at 

    has_attached_file :import_file, 
         :path => ":rails_root/public/system/:attachment/:id/:style/:filename", 
         :url => "/system/:attachment/:id/:style/:filename" 

    def initialize(args = { }) 
     args.each_pair do |k, v| 
     self.send("#{k}=", v) 
     end 
     @id = self.class.next_id 
    end 

    def update_attributes(args = { }) 
     args.each_pair do |k, v| 
     self.send("#{k}=", v) 
     end 
    end 

    def save 
     run_callbacks :save do 
     end 
    end 

    def destroy 
     run_callbacks :destroy do 
     end 
    end 

    # Needed for using form_for Importer::new(), :url => ..... do 
    def to_key 
     [:importer] 
    end 

    # Need a differentiating id for each new Importer. 
    def self.next_id 
     @@id_counter += 1 
    end 

    # Initialize beginning id to something mildly unique. 
    @@id_counter = Time.now.to_i 

    end 

一个表单文件上传可能看起来如下:

<%= form_for Importer.new, :url => import_nuts_path do |form| %> 
    <%= form.file_field 'import_file' %> 
    <%= form.submit 'Upload and Import' %> 
<% end %> 

和NutsController将有以下作用:

class NutsController < ActionController::Base 
    def import 
     importer = Importer.new(params[:importer]) 
     importer.save 
    end 
end 

注意 ::您必须调用“保存”或者什么都不会发生。调用“销毁”将删除服务器端的文件。由于这个类不是持久的,你可能应该在控制器完成之后这样做,否则如果你没有做任何清理工作,最终会导致文件空间泄露。

安全说明:此“解决方案”对new()和update_attributes()没有使用任何ActiveModel :: MassAssignmentSecurity,但该类并不真正需要它。你的旅费可能会改变。小心点!

干杯,
-Dr。极地

相关问题