错误:验证失败:图像可成像必须存在,rails-5.0,paperclip-5

Waq*_*wan 14 image-uploading paperclip ruby-on-rails-5

当我试图提交表单时,发生以下错误:Validation failed: Images imageable must exist并呈现相同的new.html.erb视图.

如果我评论了file fieldnew.html.erb.产品正在成功创建.

ProductsController的:


def new
    @product = Product.new
end

def create
    @product = Product.create!(product_params)

    if @product.save
        redirect_to products_path, notice: "Product Created Successfully"
    else
        render "new"
    end
end
def product_params
        params.require(:product).permit(:name, :quantity, :price, images_attributes: [:id, :photo, :_destroy])
end
Run Code Online (Sandbox Code Playgroud)

new.html.erb:


<%= nested_form_for @product, html: { multipart: true } do |f|%>

    <h2>New</h2>

    <P> <%= f.label :name %> <%= f.text_field :name %> </P>
    <P> <%= f.label :quantity %> <%= f.text_field :quantity %> </P>
    <P> <%= f.label :price %> <%= f.text_field :price %> </P>
  <%= f.fields_for :images do |p| %>
    <p> <%= p.label :photo %> <%= p.file_field :photo %> </p>
    <%= p.link_to_remove "Remove Image" %>
  <% end %>
  <%= f.link_to_add "Add Image", :images %>

  <%= f.submit "Add Product" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

20160725102038_add_image_columns_to_imageable.rb:


class AddImageColumnsToImageable < ActiveRecord::Migration[5.0]

  def up
    add_attachment :images, :photo
  end

  def down
    remove_attachment :images, :photo
  end

end
Run Code Online (Sandbox Code Playgroud)

型号:product.rb


class Product < ApplicationRecord
    has_one :variant
  has_many  :images, as: :imageable,  dependent: :destroy

  accepts_nested_attributes_for :images, allow_destroy: true
end
Run Code Online (Sandbox Code Playgroud)

型号:image.rb


class Image < ApplicationRecord
  belongs_to :imageable, polymorphic: true

  has_attached_file :photo, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }

end
Run Code Online (Sandbox Code Playgroud)

Waq*_*wan 32

在rails 5中,belongs_to确保必须存在关联的模型.例如,在这种多态关联中,Image模型具有 belongs_to :imageable和Product模型有关has_many :images.所以这里new.html.erb我们正在创建一个图像,但各自的产品不存在,所以这就是为什么错误Image imageable must exist.


在Image模型中建立optional: true关联时添加belong_to.

Image Model现在看起来像:

class Image < ApplicationRecord
  belongs_to :imageable, polymorphic: true, optional: true

  has_attached_file :photo, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }

end
Run Code Online (Sandbox Code Playgroud)