我有两个具有多态关联的模型(希望设置良好)。当我尝试上传文件时,我遇到了一个错误,女巫告诉我类似:NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "uploads"
我绝对没有胶水名称属性来自哪里,以及如果我将文件属性留空,为什么模型会保存。
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
这里是用于添加新事件的表单视图
<%= 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 %>
控制器是直截了当的,如 Railscast 第 196 集和第 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
更新:创建动作是普通的脚手架代码......
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
如果我只是在上传表单中插入一个标题,那么一切都会运行良好。但是,如果我也选择了一个文件,我会在保存时遇到此错误。
NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "uploads" ("created_at", "filename", "path", "title", "updated_at", "uploadable_id", "uploadable_type") VALUES (?, ?, ?, ?, ?, ?, ?)
参数对我来说看起来不错...
{"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"}
这是一个 Rails 3.2.6 应用程序。我创建了一个新的,与我的开发项目中的错误相同。