【问题标题】:Refile gem : multiple file uploadsRefile gem:多个文件上传
【发布时间】:2015-09-22 10:30:03
【问题描述】:

我正在使用带有 Rails 4 的 Refile。我正在关注他们的 multiple image upload 教程。每个帖子可以有多个图像。我的模型如下所示:

Post.rb:

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

图片.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>

如何使用多张图片上传来检索带有 refile 的图片?

【问题讨论】:

  • 这里是 attachment_image_tag 的来源:github.com/refile/refile/blob/master/lib/refile/rails/…
  • 我还忘了提到,如果我这样做@post.images.inspect,我会得到与每个具有文件 nil 的对象的关联,并且 file_id 设置为预签名,所以我认为这部分工作正常。只是当我尝试查看错误的图像时。
  • @post 是什么?它是单条记录还是记录集合?请发布@post的代码。
  • @Pavan,@post 是一条记录。我在 show.html.erb 上做了@post.inspect 并得到:#&lt;Post id: 2, name: "RefileTest", created_at: "2015-07-04 23:54:00", updated_at: "2015-07-04 23:54:00"

标签: ruby-on-rails ruby image file refile


【解决方案1】:

为了检索属于帖子的图片,您需要遍历图片数组

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

帮手attachment_image_tag取:

  • [Refile::Attachment] 对象:类的实例有一个附件
  • [Symbol] name : 附件列的名称

所以在这里,@posts.images 拥有一个 image 对象数组。就是那个有附件的对象。

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

然后当您迭代images 时,您将image object 和附件列的名称提供给助手,此处为:file

【讨论】:

  • @Frorent Ferry,这不起作用,我收到错误消息:#<:activerecord_associations_collectionproxy:0x007f8d1adb7b90> 的未定义方法“文件”
  • 您的图像迁移有“file_id:string”吗?你有没有运行“rake db:migrate”?
  • @Frorent Ferry,是的,我的 Image 模型有一个 file_id:string。它显示在我的架构文件中,因此它肯定已被迁移。
  • 所以它对我有用。您是否在强参数中设置了 images_filesparams.require(:post).permit(..., images_files: []) 如果是,我可以分享我用来写回复的 repo 应用程序。
  • @frorent Ferry,我已经在控制器中有这个了。如果你有机会,我很想看看回购,谢谢!
【解决方案2】:

你在master分支上吗?

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

【讨论】:

  • 这应该是评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
相关资源
最近更新 更多