【问题标题】:Rails - issue uploading multiple files with one form_forRails - 使用一个form_for上传多个文件的问题
【发布时间】:2013-05-31 16:35:54
【问题描述】:

我有一个创建产品页面,允许用户将多个图像添加到产品中。所以很自然地,我有许多图像上传字段,但是,当产品创建时,它只会拍摄一张照片并将其添加到数据库中。不是其他人。我犯了一些简单的错误,但我不知道它是什么。

感谢您的帮助!

新产品形态 (haml)

%h1 
  create item
= form_for @product,:url => products_path, :html => { :multipart => true } do |f|
  %p
    = f.label :name
    = f.text_field :name
  %p
    = f.label :description
    = f.text_field :description
  %p
    = fields_for :photo, :html => {:multipart => true} do |fp|
      =fp.file_field :image  
  %p
    = fields_for :photo, :html => {:multipart => true} do |fp|
      =fp.file_field :image  

  %p.button
    = f.submit

产品控制器

  def new 
    @product = Product.new
    @photo = Photo.new
  end


  def create
  @product = current_user.products.build(params[:product])
  @photo = current_user.photos.new(params[:photo])

    if @product.valid? && @photo.valid?
      @product.save
      @photo.product_id = @product.id
      @photo.save
      render "show", :notice => "Sale created!"
    else
      render "new", :notice => "Somehting went wrong!"
    end
end

【问题讨论】:

  • 使用任何宝石,如回形针上传图片。并在下面查看我的答案。它可能会帮助你。
  • 查看我的编辑。 “f.fields_for:照片”。你安装了回形针 gem 吗?
  • 是的,我用的是宝石回形针

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

您正在尝试实现嵌套属性表单。所以将 fields_for 部分更改为

%p
  = f.fields_for :photos do |fp|
    =fp.file_field :image

然后在控制器中更改您的新方法

def new 
  @product = Product.new
  3.times{ @product.photos.build }
end


def create
  @product = current_user.products.new(params[:product])
  if @product.valid?
    @product.save
    render "show", :notice => "Sale created!"
  else
    render "new", :notice => "Something went wrong!"
  end
end

你的模型应该像下面这样相关

class Product
  has_many :photos
  accepts_nested_attributes_for :photos, allow_destroy: true
end

class Photo
  attr_accessible :image
  belongs_to :product
end

如果您想为照片实现“添加更多”按钮,您可以使用 Gem nested_form。它非常好。

【讨论】:

  • 我再次查看并实现了它,它给了我 3 个图像上传字段,即使我只在 html 中放了一个,所以我猜你的答案到目前为止是有效的。但我收到此错误无法批量分配受保护的属性:photos_attributes ..这是我以前从未遇到过的。有什么想法吗?
  • 查看我在照片模型中的更改。我们必须为特定字段指定 attr_accessible。
【解决方案2】:

这里你使用了两个fields_for标签,它们生成了一个同名的输入文件元素。

所以总是只保存一个文件,因为它们的 bot 元素具有相同的名称,并且 rails 中的参数是通过使用输入元素名称传递的。 所以这里你需要使用 file_field_tag 并将参数捕获到控制器中以保存到数据库中。

【讨论】:

  • 我该怎么做。
【解决方案3】:
【解决方案4】:

服务器可以使用Gemcarrierwave,前端可以使用pluploadhttp://www.plupload.com/,非常简单

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2012-03-12
    • 1970-01-01
    相关资源
    最近更新 更多