【问题标题】:Rails upload with nested formsRails 使用嵌套表单上传
【发布时间】:2012-08-26 19:15:46
【问题描述】:

当我尝试提交一个简单的嵌套表单时,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"
}

用户控制器#update

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

图片模型

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

在哪里挖掘错误?

上面的代码是针对 Carrierwave 的,但是我尝试切换到 Paperclip 并且错误是一样的。

【问题讨论】:

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


【解决方案1】:

你说你解决了它,但我认为你一开始就做错了。

您应该将在nested_atributes_for 中使用的相同值传递给fields_for。所以 user.fields_for :pics_attributes 应该是 user.fields_for :pics

【讨论】:

  • 我尝试了您的解决方案,但如果我只将:pics_attributes 替换为:pics - 它会给我一个“无法批量分配错误”。此外,如果我在 attr_accessible 将 :pics_attributes 替换为 :pics - 它会显示 “Pic expected, got Array”
  • 我发现嵌套表单非常糟糕。也就是说,如果您有 attr_accessible :pics_attributes 并且您的关系设置正确,fields_for :pics 将起作用。如果您的表单中没有显示任何内容,那是因为没有相关的图片。您需要在控制器中构建一个新的。
猜你喜欢
  • 2016-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
相关资源
最近更新 更多