2015-07-05 28 views
13

我正在使用Refile with Rails 4.我正在按照他們的教程multiple image upload。每個帖子可以有多個圖像。我的模型是這樣的:重寫寶石:多個文件上傳

Post.rb:

has_many :images, dependent: :destroy 
accepts_attachments_for :images, attachment: :file 

Image.rb:

belongs_to :post 
attachment :file 

我可以通過上傳文件,罰款:

<%= f.attachment_field :images_files, multiple: true, direct: true, presigned: true %> 

但是當我嘗試檢索像:

<%= attachment_image_tag(@post.images, :file, :small) %> 

我得到的錯誤:

undefined method file for #<Image::ActiveRecord_Associations_CollectionProxy:0x007fbaf51e8ea0> 

我怎樣才能檢索到使用多個圖像重新提交上傳圖片?

+0

下面是attachment_image_tag來源:https://github.com/refile/refile/blob/master/lib/refile/rails/attachment_helper.rb#L39 –

+0

我也忘了提,如果我這樣做'@ post.images.inspect',我得到每個對象的文件爲nil,file_id設置爲presigned的關聯,所以我認爲這部分工作正常。這只是當我試圖查看它的錯誤圖像。 –

+0

'@ post'是什麼?它是***單個記錄***還是***記錄集合***?請發佈'@ post'的代碼。 – Pavan

回答

5

爲了取回屬於後誰的圖像,需要通過陣列圖像的迭代。

<% @post.images.each do |image| %> 
    <%= attachment_image_tag(image, :file, :fill, 300, 300) %> 
<% end %> 

助手attachment_image_tag取:

  • [重新提交::附件]對象:具有附加文件一類的實例。
  • [符號]名稱:附接柱

因此,這裏的名稱,@posts.images持有image對象的陣列。就是那個有附件的對象。

class Image < ActiveRecord::Base 
    belongs_to :post 
    attachment :file 
end 

然後,當你重複images,你給助手的image object和附件欄中的名稱,這裏:file

+0

@Frorent Ferry,這是行不通的,我得到的錯誤:未定義的方法'文件'爲#

+0

你有一個'file_id:string'你的圖片遷移?你運行'rake db:migrate'嗎? –

+0

@Frorent Ferry,是的,我的Image模型有一個file_id:string。它顯示在我的模式文件中,所以它肯定已經被遷移了。 –

0

你在主分支上嗎?

gem 'refile', require: "refile/rails", git: 'https://github.com/refile/refile.git', branch: 'master' 
+0

這應該是評論 – ketan

+0

我沒有足夠的代表評論... – Goodviber