Rails 如何基于迭代构建

Rails how to build on iteration

在尝试使用 dropzone 保存一组图像而不进行迭代之后。我切换到迭代图像并尝试保存循环。但是 rails 随地吐痰

ActiveRecord::StatementInvalid at /products =========================================== > SQLite3::ConstraintException: NOT NULL constraint failed: images.product_id: INSERT INTO "images" ("created_at", "ifoto", "product_data_id", "product_id", "updated_at") VALUES (?, ?, ?, ?, ?) app/controllers/products_controller.rb, line 214 ------------------------------------------------ ruby 209 210 if params[:images] && params[:images][:ifoto] 211 params[:images][:ifoto].values.each do |ifoto| 212 213 @image.ifoto = ifoto > 214 @image.save 215 216 217 end 218 render :nothing => true 219 App backtrace ------------- - app/controllers/products_controller.rb:214:in block (3 levels) in create' - app/controllers/products_controller.rb:211:inblock (2 levels) in create' - app/controllers/products_controller.rb:137:in `create' Full backtrace --

这是空降区代码

 format.json do
     @product = current_vitrine.products.build(params[:product])
        @image =  @product.images.build(params[:images])



if params[:images] && params[:images][:ifoto]
       params[:images][:ifoto].values.each do |ifoto|

@image.ifoto = ifoto
  @image.save


                    end
    render :nothing => true

    end
  end

有人对这类问题有提示吗?

您的问题缺少有关模型和关系的信息。 由于知之甚少,我只是猜测。 试试这个:

@product = current_vitrine.products.build(params[:product])

if @product.save
  if params[:images] && params[:images][:ifoto]
    params[:images][:ifoto].values.each do |ifoto|
      @product.images.create(ifoto: ifoto)
    end
  end
end

format.json { render :nothing => true }