当使用Rails 4和嵌套表单时,Carrierwave仅在更新操作时上载图像

时间:2013-08-19 17:40:13

标签: ruby-on-rails-4 carrierwave strong-parameters

我的模特:

class Product < ActiveRecord::Base
  has_many :product_images, dependent: :destroy
  accepts_nested_attributes_for :product_images, :reject_if => lambda { |p| p['image'].blank? }, :allow_destroy => true
end


class ProductImage < ActiveRecord::Base
  belongs_to :product
  mount_uploader :image, ProductImageUploader
  validates_presence_of :image
end

我的控制器:

  def create
    @product = Product.new(permitted_params.product)
    if @product.save
        redirect_to edit_admin_product_path(@product), notice: "success"
    else
      render :new
    end
  end

  def update
    @product = Product.find(params[:id])
    if @product.update_attributes(permitted_params.product)
      redirect_to edit_admin_product_path(@product), notice: "success"
    else
      render :edit
    end
  end

permitted_pa​​rams:

class PermittedParams < Struct.new(:params)
  def product
    params.require(:product).permit(*product_attrs)
  end

  def product_attrs
    [:name, :content, :stock, :list_price, :selling_price, :bonus, :is_added,
     product_images_attributes: [:id, :image, :_destroy] ]
  end
end

参数传递:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"eqweq1231sda+3T0131643guXybT75X6NqN1ng=", "product"=>{"name"=>"weqwe", "content"=>"qweq", "product_images_attributes"=>{"0"=>{"image"=>"1069218_513152615405563_1187314087_n.jpg", "_destroy"=>""}}, "stock"=>"", "list_price"=>"", "selling_price"=>"123", "bonus"=>""}, "commit"=>"submit"}

显然,图像传递给了参数。但是当创建产品时,它将回滚以警告图像为空(在我的ProductImage模型中验证存在图像)。

如果我删除验证,则创建产品。我可以在更新操作中成功上传图像。我完全不知道这是什么问题!请帮忙。 Q_Q

0 个答案:

没有答案