2011-08-16 36 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