0

I am uploading images which POSTs the following params:

Parameters: {"url"=>"https://bucket.s3.amazonaws.com/image014.jpg",
"filepath"=>"/uploads%2F1381509934146-1t5a44loikwhr529-1d68490743e05a1287fea45ed4ed9e59%2Fslide0005_image014.jpg",
"filename"=>"slide0005_image014.jpg", 
"filesize"=>"30807", 
 "filetype"=>"image/jpeg", 
 "unique_id"=>"1t5a44loikwhr529", 
 "choice"=>["https://bucket.s3.amazonaws.com/image014.jpg"]}

And here is my form:

<%= s3_uploader_form callback_url: choices_url, callback_param: "choice[]", id: "s3-uploader" do %>
  <%= file_field_tag :file, multiple: true %>
   <button type="submit" class="btn btn-primary start"> 
<% end %>

And in my controller I have:

#app/controllers/choices_controller

def create
@choice = Choice.create!(choice_params)
  if @choice.persisted?
    respond_to do |format|
      format.html { redirect_to choices_path }
      format.json { head :no_content }
    end
  end
end

def choice_params
  params.require(:choice).permit(:url, :filepath, :filename, :filesize, :filetype)
end

But, it returns the error:

 NoMethodError (undefined method `permit' for #<Array:0x007f903e380060>):
  app/controllers/choices_controller.rb:49:in `choice_params'
  app/controllers/choices_controller.rb:24:in `create'

Can you tell me what I am doing wrong here? All I would like to do is:

1) Add the "url" param to the DB 2) Titlelize the "filename" param and then submit that to the DB.

Thanks very much!

4

1 回答 1

1

为什么 ?

require像 一样工作params[:some_key],除了它ActionController::ParameterMissing在返回的值为空白时引发。

这很方便,因为它允许在这种情况下使用rescue_from, 来呈现400: bad request错误。

该怎么办 ?

所以你必须包装你的参数,这样当你打电话时require(:choice)你会得到一个哈希值。

不幸的是s3_upload_form,它似乎不支持与相同的构建器语法form_for,这将允许您执行以下操作:

<%= form_for :s3_upload do |f| %>
    <% f.file_field :file %>
<% end %>

导致这样的参数哈希:

 { s3_upload: {file: <SomeFile ...>} }

所以我的建议只是放弃require调用,并把:choice传递给permit.

如果您希望仍然拥有该require方法的好处(即检查是否缺少参数),您总是可以按照以下方式做一些事情:

def choice_params
  params.permit(:foo, :bar, :baz).tap do |p| 
    p.each_key{ |k| p.require k }
  end
end

如果缺少任何允许的参数,这将引发异常。

于 2013-10-11T17:18:41.930 回答