错误:验证失败:图像必须存在于imageable中,rails-5.0,paperclip-5。

15

在我尝试提交表单时,出现以下错误:验证失败:必须存在图片imageable并且渲染相同的 new.html.erb 视图。

如果我在new.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

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 %>

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

Model:product.rb


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

  accepts_nested_attributes_for :images, allow_destroy: true
end

Model: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
1个回答

38

在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 模型如下:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接