Reputation: 61
I'm trying to save a model called Upload that has a polyformic association called uploadable.
Now I'm doing a dropzone js area where users can drag and drop the files and it should create the upload on server side and then return some keys that will be added in the html and will be used only if the user save the form(if user save the form I will set the uploadable_id and uploadable_type with the comment just created or otherwise the upload will be automatically deleted within 24h with a cronjob)
The only problem that I have is that rails automatically wants that uploadable_id e uploadable_type are present when I do @upload.save
How can I skip the validation (of presence) only for the uploadable attribute ? I want avoid to use @upload.save(validate: false) because it skips all the validations and not just one.
I've tried using a fake attribute:
class Upload < ApplicationRecord
belongs_to :uploadable, polymorphic: true
has_attached_file :file
attr_accessor :skip_uploadable_validation
validate :uploadable, unless: :skip_uploadable_validation
end
And then I do:
@upload = Upload.new
@upload.file = params[:file]
@upload.skip_uploadable_validation = true
@upload.save # it fails anyway
But it doesn't works.
Upvotes: 2
Views: 2402
Reputation: 2624
You can puts optional: true
to this line:
belongs_to :uploadable, polymorphic: true, optional: true
Or using this way:
with_options unless: :skip_uploadable_validation do
validates :uploadable_id, presence: true
validates :uploadable_type, presence: true
end
Upvotes: 6