Posted over 8 years ago. Visible to the public. Repeats.

Copying validation errors from one attribute to another

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

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:

Copy
class Note < ActiveRecord::Base has_attached_file :attachment validates_attachment_presence :attachment validates_format_of :attachment_file_name, :with => /^\d+\.jpg$/ include DoesCopyErors[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:

Copy
include DoesCopyErors[from: :attachment_file_name, to: :attachment, move: true]

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Dominik Schöler
Attachments:
does_copy_errors.rb
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more