Error: Validation failed: Images imageable must exist , rails-5.0 , paperclip-5

前端 未结 1 1937
北恋
北恋 2021-02-07 13:56

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.

1条回答
  •  难免孤独
    2021-02-07 14:01

    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
    

    0 讨论(0)
提交回复
热议问题