Adding :multipart => true throws Undefined Method “name” error

不打扰是莪最后的温柔 提交于 2019-12-02 01:22:06

Well, I finally buckled down and traced my way through the ActiveRecord source code via logger outputs. Turns out, as I suspected, it was failing to save the UploadedFile because it couldn't convert it to YAML.

However, this because of a stupid mistake on my part. In my submitting form, I had:

<%= f.file_field :picture_file_name %>

When it should have been:

<%= f.file_field :picture %>

The paperclip gem understands that :picture is the uploaded file and works the background magic to save the file name to the proper field. I just underestimated the ease of use I guess!

Normally, I would delete the question for something this trivial, but seeing as I made this mistake, others probably will in the future, and there was very little out there to point me to the solution. So I will keep it up to aid in the future googling of similarly dense developers!

After lot of searching and debugging. The main symptom of this problem is that form with a file field are being made as multipart form and rails 3.2 is not able to save the data because it is trying to save other parameters that are not present in your database (The filed for the file object).

Taking the appopriate values and saving them to some variable and removing the file hash from the params has seems to work around the issue!

Here is an example of a working code to save in the database using rails 3.2

file = params[:document][:file].tempfile.read
params[:document].delete(:file)
@document = Document.new(params[:document])   
respond_to do |format|
  if @document.save
@document.file = file
@document.save
    format.html { redirect_to @document, notice: 'Document was successfully created.' }
    format.json { render json: @document, status: :created, location: @document }
  else
    format.html { render action: "new" }
    format.json { render json: @document.errors, status: :unprocessable_entity }
  end
end

You didn't post it, but I think you should go with :html => { :multipart => true } instead of just :multipart => true in your form, like:

form_for object, :html => { :multipart => true } do |o|
    ...
Travis Dahl

I had spent about a week on the same error, even though I had the correct fields.

The silliness causing all my headaches was simply the order of tags in the view.

Caused Error

NoMethodError in DatenightsController#create undefined methodname' for nil:NilClass:

<%= f.file_field :photo %>
<%= f.text_field :name %>

Solution for above quoted Error (Just the sequence/order matters a lot here)

<%= f.text_field :name %>
<%= f.file_field :photo %>

Since the issue took so much of my sweet time I thought it may help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!