我的模型:
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
允许的参数:
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 模型中验证存在图像)。
如果我删除验证然后创建产品。我可以在更新操作中成功上传图像。我完全不知道有什么问题!请帮忙。QQ