1

多形の関連付けを持つ2つのモデルがあります(うまくいけばうまく設定されています)。エラーウィッチで実行したファイルをアップロードしようとすると、次のような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"}

これはRails3.2.6アプリです。開発プロジェクトと同じエラーで新しいものを作成しました。

4

1 に答える 1

1

私は同様の問題を扱っています。保存する前に、ファイルオブジェクトをparamsハッシュ内のファイルの名前に置き換える必要があると思います。params ['event']['filename']はActionDispatch::Http :: UploadFileオブジェクトであり、おそらくその値を文字列にする必要があります。

于 2012-07-31T00:39:34.480 に答える