rails undefined方法`[]'为nil:关联时为NilClass

时间:2017-02-15 19:55:18

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

在保存产品后立即放置一个关联图像,导轨为nil:NilClass的方法`[]'吐出,为什么显示nil,对于已经建立的关联?

def create

  @product = current_square.products.build(params[:product])
  @images = @product.images.build
  respond_to do |format|
    format.html do
      if @product.save  
        params[:images]['ifoto'].each do |a|
          @images = @product.images.create!(:ifoto => a)
        end
      end
    end
  end

end

1 个答案:

答案 0 :(得分:-2)

我认为这是关于这个问题的第二个问题。 请阅读一些关于保存关联的教程:

http://www.railscook.com/recipes/multiple-files-upload-with-nested-resource-using-paperclip-in-rails/

http://www.discretelogix.com/blog/ruby-rails/uploading-multiple-files-with-carrierwave-in-rails-4

您的方法可能应如下所示:

def create
  @product = current_square.products.build(params[:product])

  respond_to do |format|
    format.html do
      if @product.save
        if params[:images] && params[:images]['ifoto']
          params[:images]['ifoto'].each do |foto|
            @images = @product.images.create!(ifoto: foto)
        end
      end
    end
  end
end