在params中传递数组并在Rails中创建行

时间:2014-01-01 22:58:23

标签: ruby-on-rails ruby-on-rails-3.2

如何在params中迭代数组并在数据库中为每个项创建行?我想用下面的代码来实现它:

  def create
    @attachment = @project.attachments.new(params[:attachment][:file])

    respond_to do |format|
      if @attachment.save
        format.json { render json: {files: [@attachment]}, status: :created, location: [@project, @attachment] }
      else
        format.json { render json: @attachment.errors, status: :unprocessable_entity }
      end
    end
  end

但每次我收到此错误:

NoMethodError at /projects/10/attachments
=========================================

> undefined method `stringify_keys' for #<ActionDispatch::Http::UploadedFile:0x00000005867d38>

app/controllers/attachments_controller.rb, line 46
--------------------------------------------------

``` ruby
   41     end
   42   
   43     # POST /attachments
   44     # POST /attachments.json
   45     def create
>  46       @attachment = @project.attachments.new(params[:attachment][:file])
   47   
   48       respond_to do |format|
   49         if @attachment.save
   50           format.json { render json: {files: [@attachment]}, status: :created, location: [@project, @attachment] }
   51         else
```

App backtrace
-------------

 - app/controllers/attachments_controller.rb:46:in `create'
 - script/rails:6:in `<top (required)>'
 - script/rails:0:in `<main>'

这就是我的参数的样子: params

最后我的模特:

class Attachment < ActiveRecord::Base
  attr_accessible :file, :project_id, :issue_id, :attachment
  resourcify
  mount_uploader :file, AttachmentsUploader
end

我该如何解决?提前谢谢!

1 个答案:

答案 0 :(得分:0)

new方法采用哈希:

@project.attachments.new(file: params[:attachment][:file])