2011-08-16 35 views
40

我使用Active admin作为我的Rails应用程序后端。我想做一个文件上传。我怎样才能完成这个功能?Activeadmin Rails使用回形针上传文件

+0

我从来没有使用主动联系具体来说,但回形针宝石帮助您可以轻松上传文件并将其附加到任何型号。 https://github.com/thoughtbot/paperclip – airlok

回答

74

我发现了一种在Active Admin中使用Paperclip的方法。

我在我的模型“事件”添加以下代码:

has_attached_file :map, :styles => { :medium => "238x238>", 
            :thumb => "100x100>" 
           } 

而且我这样做对我的管理模式:

ActiveAdmin.register Event do 
form :html => { :enctype => "multipart/form-data" } do |f| 
    f.inputs "Details" do 
    f.input :continent 
    f.input :event_type 
    f.input :name 
    f.input :title 
    f.input :content 
    f.input :date_start, :as => :date 
    f.input :date_end, :as => :date 
    f.input :place 
    f.input :map, :as => :file 
    f.input :image, :as => :file, :hint => f.template.image_tag(f.object.image.url(:medium)) 
    f.input :userfull_info 
    f.input :price 
    f.input :phone, :as => :phone 
    f.input :website, :as => :url 
    end 
    f.buttons 
end 
end 

索引页上使用它,你必须使用:

column "Image" do |event| 
    link_to(image_tag(event.image.url(:thumb), :height => '100'), admin_event_path(event)) 
    end 
    default_actions 
end 
+4

你可以使用f.input:image,:hint =>“当前图像:#{f.template.image_tag(f.object.image.url(:thumb))} “ – Nazar

+0

默认情况下使用回形针将此上传到s3吗? – JehandadK

+2

我不得不使用“f.actions”,而不是“f.buttons”才能使其工作。 – Joseph

6

我使用的铁轨3.0.1和下面的代码

f.input :image, :hint => "current image: #{f.template.image_tag(f.object.image.url(:thumb))}" 

返回一个字符串。搜索解决方案后,我找到了它。

f.input :image, :hint => f.template.image_tag(f.object.image.url(:thumb)) 

直接发送对象,将一个图像返回HTML

+2

您可以使用第一行代码,只需在字符串上调用'html_safe'(在双引号之后)。 –

5

在ActiveAdmin的版本最新&轨道4的显示文件领域,我们需要使用下面的代码

以前我们使用f.input:上传,:为=>:文件

ActiveAdmin.register Project do 
    permit_params :name, :uploads 


    form multipart: true do |f| 
    f.inputs "Project Details" do 
     f.input :name 
     f.input :uploads, required: false 
    end 
    f.actions 
    end 

end 
13

得到它的工作为Rails 4.1和4.1回形针:

型号

class Hotel < ActiveRecord::Base 

has_attached_file :thumbnail, :styles => { :medium =>  "300x300#", :thumb => "200x200#" } 
validates_attachment :thumbnail, content_type: { content_type:  ["image/jpg", "image/jpeg", "image/png"] } 

end 

管理模式

ActiveAdmin.register Hotel do 

permit_params :name, :description, :price, :thumbnail 

form do |f| 
    f.inputs "Project Details" do 
    f.input :name 
    f.input :thumbnail, :required => false, :as => :file 
    # Will preview the image when the object is edited 
    end 
    f.actions 
end 

show do |ad| 
    attributes_table do 
    row :name 
    row :thumbnail do 
     image_tag(ad.thumbnail.url(:thumb)) 
    end 
    # Will display the image on show object page 
    end 
end 
end 
+0

我得到了'paperclip NoHandlerError',我不得不'form:html => {:multipart => true} do | f |' – givanse

+0

@givanse你必须做'form:html ...'在哪里? – Aleks