Rails上传嵌套表单

时间:2012-08-24 12:58:43

标签: ruby-on-rails ruby-on-rails-3 paperclip carrierwave

当我尝试提交一个简单的嵌套表单时,Rails会给我一个错误:

NoMethodError in UserController#update
undefined method `[]' for #<ActionDispatch::Http::UploadedFile:0x3f4e318>

而且参数是:

{
 "utf8"=>"✓",
 "authenticity_token"=>"HFWawKp4RH7+AFV0yQ1cXpzxHDfubKTKkiDiS6QKnJk=",
 "user"=> { 
  "name"=>"Alex",
  "pics_attributes"=> { 
    "pic"=>#<ActionDispatch::Http::UploadedFile:0x3f4e318
    @original_filename="Beautiful Sky_thumb.jpg",
    @content_type="image/jpeg",
    @headers="Content-Disposition: form-data; name=\"user[pics_attributes][pic]\"; filename=\"Beautiful Sky_thumb.jpg\"\r\nContent-Type: image/jpeg\r\n",
    @tempfile=#<File:C:/Users/Alex/AppData/Local/Temp/RackMultipart20120824-4784-5rmxid>>
  }
 },
"commit"=>"Save User"
}

UserController的#更新

def update
 @user = User.new(params[:user])
 @user.save
end

表单(它使用通用表单构建器。可能会导致错误?)

<%= form_for :user, url: '/user/update', html: {multipart: true} do |user| %>
  <%= user.hidden_field :name, {value: 'Alex'} %>
  <%= user.fields_for :pics_attributes do |pic| %>
    <%= pic.file_field :pic %>
  <% end %>
  <%= user.submit %>
<% end %>

用户模型

class User < ActiveRecord::Base
  attr_accessible :name, :pics_attributes
  has_many :pics
  accepts_nested_attributes_for :pics
end

Pics模型

class Pics < ActiveRecord::Base
  belongs_to :user
  attr_accessible :image
  mount_uploader :image, PicUploader
end

在哪里挖掘错误?

上面的代码适用于Carrierwave,但我尝试切换到Paperclip并且错误是相同的。

1 个答案:

答案 0 :(得分:1)

你说你解决了它,但我认为你首先做错了。

您应该将nested_atributes_for中使用的相同值传递给fields_for。因此 user.fields_for :pics_attributes应为user.fields_for :pics