轨道,删除属性"undefined method '[]' for nil:NilClass"时无法更新以与茧一起工作?



我想知道有人可以告诉我为什么我会遇到这个错误"未定义的方法'[]'for nil:nilclass'。当我用茧删除图片并尝试更新时,就会发生这种情况。该方法可用于将图片添加到编辑的画廊中,但是在删除和更新时我会遇到此错误。我尝试使用unless @pictures.blank? end,假设问题是茧删除图片时,但我不确定该怎么做。服务器错误是

Started PATCH "/galleries/41" for ::1 at 2017-05-07 16:03:02 +1000
Processing by GalleriesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"cG1UXCvODhYzqqAr++EAn8GvMVk7+t/eASkzDDOoPmJfw3l6ax/F2xXMhvs7FcrJ3LOuTd0sks5+2fb86kQv0Q==", "gallery"=>{"name"=>"Hellooo", "cover"=>"123456", "pictures_attributes"=>{"0"=>{"_destroy"=>"1", "id"=>"47"}, "1"=>{"_destroy"=>"1", "id"=>"48"}}}, "commit"=>"Update Gallery", "id"=>"41"}
  Gallery Load (0.0ms)  SELECT  "galleries".* FROM "galleries" WHERE "galleries"."id" = ? LIMIT ?  [["id", 41], ["LIMIT", 1]]
Unpermitted parameter: pictures_attributes
   (0.0ms)  begin transaction
  User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  (0.0ms)  commit transaction
Completed 500 Internal Server Error in 4ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `[]' for nil:NilClass):
...

也许有人可以向我解释这会很棒!

_form.html.erb

<%= form_for(@gallery, multipart: true) do |f| %>
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :cover %>
    <%= f.text_field :cover %>
  </div>
  <div id="pictures">
    <%= f.fields_for :pictures do |pic| %>
    <%= render 'picture_fields', f: pic %>
  </div>
  <% end %>
    <div class="links">
      <%= link_to_add_association 'add picture', f, :pictures %>
  <%= f.submit %>
  </div>
<% end %>

_picture_fields.html.erb

<div class="nested-fields">
  <div class="field">
    <%= f.label :picture %>
    <%= f.file_field :picture, multiple: true, name: "pictures[picture][]" %>
    <%= link_to_remove_association "remove picture", f %>
  </div>
</div>

GalleriesController

def update
    @gallery = Gallery.find(params[:id])
    if @gallery.update(gallery_params)
       params[:pictures][:picture].each do |pic|
       @pictures = @gallery.pictures.create!(picture: pic)
      end
      flash[:success] = "Gallery Updated!"
      redirect_to root_url
    else
      render 'edit'
    end
  end

编辑:添加Gallery_params

def gallery_params
   params.require(:gallery).permit(:id, :name, :user_id, :cover, picture_attributes: [:id, :gallery_id, :picture, :_destroy])
  end

编辑:添加了使用Cocoon

添加创建动作和服务器日志
 def create
    @user = User.first
    @gallery = @user.galleries.build(gallery_params)
    if @gallery.save       
       flash[:success] = "Picture created!"
       redirect_to root_url
    else
     render 'new'
   end
 end

服务器日志

Started POST "/galleries" for ::1 at 2017-05-10 13:18:43 +1000
Processing by GalleriesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"XU3z2jMdbselPJZ2SdZdGPwiAebiPznt8GWRqmbv8LM/MIxO+sNo1z2NTaDQ3nJNm0qaBJ66ny5254MPpHZaQQ==", "gallery"=>{"name"=>"Hello", "cover"=>"123456", "pictures_attributes"=>{"1494386318553"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xac59228 @tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170510-7596-16xlrir.jpg>, @original_filename="Skateboard 1.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name="gallery[pictures_attributes][1494386318553][picture]"; filename="Skateboard 1.jpg"rnContent-Type: image/jpegrn">, "_destroy"=>"false"}, "1494386321001"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xac59150 @tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170510-7596-jxo0st.jpg>, @original_filename="Skateboard 2.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name="gallery[pictures_attributes][1494386321001][picture]"; filename="Skateboard 2.jpg"rnContent-Type: image/jpegrn">, "_destroy"=>"false"}}}, "commit"=>"Create Gallery"}
  User Load (0.0ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
   (0.0ms)  begin transaction
  User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.0ms)  rollback transaction
  Rendering galleries/new.html.erb within layouts/application
  Rendered galleries/_picture_fields.html.erb (1.0ms)
  Rendered galleries/_picture_fields.html.erb (0.5ms)
  Rendered galleries/_picture_fields.html.erb (0.5ms)
  Rendered galleries/_form.html.erb (42.0ms)
  Rendered galleries/new.html.erb within layouts/application (58.5ms)
Completed 200 OK in 157ms (Views: 139.3ms | ActiveRecord: 0.0ms)

mmmm。使困惑。没有params[:pictures],因此显然是nil(检查您在顶部发布的日志(。因此,这会导致错误。如果您正在寻找发布的图片,则应参考params[:pictures_attributes],但不确定您要在那里做什么:为每张发布的图片创建一个空图(再次?(?图片是通过执行gallery.update(gallery_params)保存的。

注意:通过已发布的参数进行迭代肯定是错误的,因为如果删除了一个,则将其保留在嵌套参数_destroy设置为true中,因此可以从数据库中正确删除,或者如果已经图片已经删除存在,它也将再次发布(由于已经存在,因此没有保存(。

[编辑]添加简短解决方案:

  • 在您的视图中使用f.fields_for :pictures:这将在画廊拥有的现有图片上迭代,并允许删除/编辑现有,并在画廊中添加新图片
  • 修复您的gallery_params并允许pictures_attributes(而不是单数形式((否则什么也没有保存(
  • 在您的控制器中,只需编写@gallery.update_attributes(gallery_params),并且根本不迭代params[:pictures](删除该部分(,它应该只是工作(因为update_attributes已经完成了此操作,至少在您想手动使用pictures_attributes时(

看起来您的 gallery_params方法不允许您的pictures_attributes。您没有发布该代码,但是我在错误日志Unpermitted parameter: pictures_attributes中注意到,这意味着您的强参数(Gallery_params方法(正在滤除这些参数。

基本上,强参数的全部要点是确保您仅通过实际想要通过的键。因此,您的控制器就像"没人告诉我我应该收取picture_attributes,所以我不允许他们通过。"然后,您的代码期望在图片数组中有一个图像对象,但是图片阵列没有引起错误的图片对象。

您可以发布图库参数的代码吗?您还可以发布参数的内容吗?全面披露:我真的不知道Rails 5,所以可能还有其他一些事情。

相关内容

最新更新