undefined method `[]' for #<ActionDispatch::Http::UploadedFile:0x007fae8c0bfaa8>

梦想与她 提交于 2019-12-01 20:38:39

问题


I have nested form with the file_field column, when i try to create it throws NoMethodError in UserController#update undefined method `[]' for #

{
 "utf8"=>"✓",
 "authenticity_token"=>"HFWawKp4RH7+AFV0yQ1cXpzxHDfubKTKkiDiS6QKnJk=",
 "user"=> { 
  "name"=>"Test",
  "image_attributes"=> { 
    "picture"=>#<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"
}

My Model

class User < ActiveRecord::Base
  attr_accessbile: :name, image_attributes
  has_many :images
  accepts_nested_attributes_for: images
end

class Image < ActiveRecord::Base
  belongs_to :verve_app
  mount_uploader picture, PictureUploader
end

My controller

def new
  @user = User.new
  @user.images.build
end

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

My view

<%= form_for @user do |f| %>
  <%= f.hidden_field :name, {value: 'Alex'} %>
  <%= f.fields_for :image_attributes do |image| %>
    <%= image.file_field :picture %>
  <% end %>
  <%= user.submit %>
<% end %>

回答1:


Try calling fields_for on the model class :image rather than on :image_attributes.

Replace your <%= f.fields_for :image_attributes do |image| %> with <%= f.fields_for :image do |i| %>. Then change image.file_field to i.file_field

See if this helps, or at least produces new error for us to work from.




回答2:


In the View, change :image_attributes to :images The rest of your code is correct and this change should make it work. If you want to ave multiple instances of the children (images) just build that many in your controller.

Here's a related ticket where you can see examples: Plural for fields_for has_many association not showing in view




回答3:


Don't forget that your model class should contain the hook for the uploader :-)

mount_uploader :picture, PictureUploader



回答4:


Is it possibly because the form needs to read:

<% f.fields_for :images_attributes do |image| %> (Note the plural)

It's my understanding that in the call to x_attributes, x needs to match how the attributes were declared in the model. In this case, it was set up accepts_nested_attributes_for :images



来源:https://stackoverflow.com/questions/21156232/undefined-method-for-actiondispatchhttpuploadedfile0x007fae8c0bfaa8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!