Read more

Copying validation errors from one attribute to another

Henning Koch
September 14, 2010Software engineer at makandra GmbH

When using virtual attributes, the attached trait Show archive.org snapshot can be useful to automatically copy errors from one attribute to another.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Here is a typical use case where Paperclip creates a virtual attribute :attachment, but there are validations on both :attachment and :attachment_file_name. If the form has a file picker on :attachment, you would like to highlight it with errors from any attribute:

class Note < ActiveRecord::Base
  has_attached_file :attachment
  validates_attachment_presence :attachment
  validates_format_of :attachment_file_name, :with => /^\d+\.jpg$/
  include DoesCopyErrors[from: :attachment_file_name, to: :attachment]
end

If you'd like to remove the errors from the source attribute once they are copied to the target attribute, you can use the :move option:

include DoesCopyErors[from: :attachment_file_name, to: :attachment, move: true]
Posted by Henning Koch to makandra dev (2010-09-14 18:01)