2016-07-26 4 views
11

जबकि मैं फॉर्म सबमिट करने का प्रयास कर रहा था, त्रुटि के बाद: Validation failed: Images imageable must exist और उसी new.html.erb व्यू को प्रस्तुत करें।त्रुटि: प्रमाणीकरण विफल: चित्र छवियों का अस्तित्व होना चाहिए, रेल-5.0, पेपरक्लिप -5

यदि मैं new.html.erb में file field पर टिप्पणी करता हूं। उत्पाद सफलतापूर्वक बनाया जा रहा है।

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 

मॉडल: product.rb


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

    accepts_nested_attributes_for :images, allow_destroy: true 
end 

मॉडल: 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 

उत्तर

24

रेल में 5, belongs_to सुनिश्चित करता है कि संबंधित मॉडल मौजूद होना चाहिए। ई.g इस बहुलक संघ में, छवि मॉडल में belongs_to :imageable है और उत्पाद मॉडल में has_many :images है। तो यहां new.html.erb में हम एक छवि बना रहे हैं, लेकिन संबंधित उत्पाद मौजूद नहीं है, इसलिए त्रुटि Image imageable must exist है।

समाधान


optional: true जबकि छवि मॉडल में belong_to का एक संघ बनाने जोड़ें।

छवि मॉडल अब लगता है कि:

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 
संबंधित मुद्दे