While i was trying to submit the form, following error occured: Validation failed: Images imageable must exist
and render the same new.html.erb
view.
In rails 5, belongs_to
makes sure that the associated model must exist.
E.g In this polymorphic association, Image model has belongs_to :imageable
and Product model has has_many :images
.
So here in new.html.erb
we are creating an image, but respective product not exist, so that's why error Image imageable must exist
.
Solution
Add optional: true
while making an association of belong_to
in Image model.
Image Model now looks like:
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