I've two models with a polymorphic association (hopefully set up well).
When I try to upload a file I run in an error witch tells me something like: NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "uploads"
I have absolut no glue where the name attribute comes from and why the model saves if I left the file attribute empty.
class Event < ActiveRecord::Base
attr_accessible :title,
:uploads_attributes
has_many :uploads, :as => :uploadable
accepts_nested_attributes_for :uploads
end
class Upload < ActiveRecord::Base
attr_accessible :filename, :path, :title
belongs_to :uploadable, :polymorphic => true
end
Here the form views for adding new events with uploads
<%= form_for(@event) do |f| %>
<div class="field">
<%= f.text_area :title, :rows => 4 %>
</div>
<div>
<%= f.fields_for :uploads do |builder| %>
<div><%= builder.text_field :title %></div>
<div><%= builder.file_field :filename %></div>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
The controller is straight forward like shown in Railscast episodes #196 and #197
def new
@event = Event.new
@event.uploads.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @event }
end
end
update: The create action is plain vanilla scaffolding code...
def create
@event = Event.new(params[:event])
respond_to do |format|
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render json: @event, status: :created, location: @event }
else
format.html { render action: "new" }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
If I just insert a title to the Upload form all things running well. But if I select a file as well I run in this error on saving.
NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "uploads" ("created_at", "filename", "path", "title", "updated_at", "uploadable_id", "uploadable_type") VALUES (?, ?, ?, ?, ?, ?, ?)
The parameters looking fine for me ...
{"utf8"=>"✓",
"authenticity_token"=>"ppPQnkqXPSbNzRU4KGW11EpzktONZC2DS+hkRQAOnlM=",
"event"=>{"title"=>"Erstes",
"uploads_attributes"=>{"0"=>{"title"=>"foo",
"filename"=>#<ActionDispatch::Http::UploadedFile:0x00000003a2d548 @original_filename="Hazard_E.svg",
@content_type="image/svg+xml",
@headers="Content-Disposition: form-data; name=\"event[uploads_attributes][0][filename]\"; filename=\"Hazard_E.svg\"\r\nContent-Type: image/svg+xml\r\n",
@tempfile=#<File:/tmp/RackMultipart20120721-25352-1ioiss9>>}}},
"commit"=>"Create Event"}
This is a Rails 3.2.6 app. I've create a new one with the same error as in my development project.