Ruby on Rails 4和Paperclip

时间:2015-08-20 17:12:09

标签: ruby-on-rails ruby image ruby-on-rails-4 paperclip

我正在使用rails构建项目,它是一家公司的虚拟商店。用户应该能够注册新产品并上传图像,因此我生成了两个模型:“产品”和“图像”,产品has_many图像和图像belongs_to产品,我已经运行了paperclip来更新图像。 “accepts_nested_attributes_for :images”在产品型号中,因此我可以保存来自同一产品表单的图像。问题是图像没有被保存。用户应该能够上传3张图片(这就是我允许的方式“3.times {@product.images.build}”)。这是我的产品总监:

def new
    @product = Product.new
    3.times {@product.images.build}
 end

 def create
     @product = Product.new(params[:product])
     if @product.save
        redirect_to :root
     else
        render :action => 'new'
     end
 end

我也尝试过这样定义product_params方法:

private
    def product_params
        params.require(:product).permit(:title, :info, :description, :price, :images_attributes => [])
    end

这是控制台中抛出的请求信息:

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"qRyYjG9pSaFxgCtMddDN3fpbsTeIAagLEz+psd+Z+oHa2AVjXpXYcbxta/Egj2TGrmF3FFNCllkY54dig3aN8g==",
 "product"=>{"title"=>"Title",
 "info"=>"Infor",
 "description"=>"Description",
 "price"=>"9",
 "images_attributes"=>{"0"=>{"photo"=>#<ActionDispatch::Http::UploadedFile:0xad3d830 @tempfile=#<Tempfile:/tmp/RackMultipart20150820-9643-h6wdta.png>,
 @original_filename="sticker,
375x360.u1.png",
 @content_type="image/png",
 @headers="Content-Disposition: form-data; name=\"product[images_attributes][0][photo]\"; filename=\"sticker,
375x360.u1.png\"\r\nContent-Type: image/png\r\n">},
 "1"=>{"photo"=>#<ActionDispatch::Http::UploadedFile:0xad3d704 @tempfile=#<Tempfile:/tmp/RackMultipart20150820-9643-19t1r3v.png>,
 @original_filename="sticker,
375x360.u1.png",
 @content_type="image/png",
 @headers="Content-Disposition: form-data; name=\"product[images_attributes][1][photo]\"; filename=\"sticker,
375x360.u1.png\"\r\nContent-Type: image/png\r\n">},
 "2"=>{"photo"=>#<ActionDispatch::Http::UploadedFile:0xad3d650 @tempfile=#<Tempfile:/tmp/RackMultipart20150820-9643-fj3w5g.png>,
 @original_filename="sticker,
375x360.u1.png",
 @content_type="image/png",
 @headers="Content-Disposition: form-data; name=\"product[images_attributes][2][photo]\"; filename=\"sticker,
375x360.u1.png\"\r\nContent-Type: image/png\r\n">}}},
 "commit"=>"Submit"}

如果我将方法product_params作为@product = Product.new(product_params)中的参数传递,则会保存标题,说明和价格,但不保存图像。

1 个答案:

答案 0 :(得分:1)

您保留了:images_attributes => [],但应该是:images_attributes => [:image]

所以,改变一下:

params.require(:product).permit(:title, :info, :description, :price, :images_attributes => [])

为:

params.require(:product).permit(:title, :info, :description, :price, :images_attributes => [:image])

product_params方法中。

之后它应该有效!

对于图像验证,请使用:

validates_attachment_presence :image

如果此验证不起作用,请尝试使用如下自定义验证:

  validate :image_present

  def image_present
    if image_file_name.blank?
      errors.add(:image, :image not present")
    end
  end