0

I am using Ruby on Rails 3.1.0 and the Paperclip gem. I would like to change the normal behavior to validate and add error messages to a class object.

That is, an invalid instance of a User class is (the :avatar_file_size error is related to the Paperclip gem)

#<ActiveModel::Errors:0x0000010166cfb8 @base=#<User id: 1, firstname: "Sample firstname", lastname: "Sample lastname", avatar_file_name: "avatar_file.jpg",
...>, @messages={:avatar_file_size=>["is too big"]}>

I would like to have the following output (note that the :avatar_file_size error-hash key is changed to :avatar):

#<ActiveModel::Errors:0x0000010166cfb8 @base=#<User id: 1, firstname: "Sample firstname", lastname: "Sample lastname", avatar_file_name: "avatar_file.jpg",
...>, @messages={:avatar=>["is too big"]}>

In few words, what I would like to do is to change the error-hash key related to the error message generated by the Paperclip gem.

How can I do that?


Maybe it is possible to do that directly in the validates method present in the User model that at this time is:

validates_attachment_size :avatar,
  :less_than => 4.megabytes,
  :message   => "is too big"
Backo
  • 18,291
  • 27
  • 103
  • 170

1 Answers1

0

You can supply an option called message to override the default message. I am assuming you are using the paperclip gem's size validator.

validates_attachment_size :avatar, :less_than => 5.megabytes, 
                            :message => "is too big"
Harish Shetty
  • 64,083
  • 21
  • 152
  • 198
  • 1
    I don't want to change the validation message but the key name (from ':avatar_file_size' to ':avatar') of the array where normally the message will be inserted. – Backo Sep 21 '11 at 04:28
  • You don't write the validator on the `avatar_file_size` column ( as it is a meta column for Paperclip). You write the validation for :avatar. As I have shown above the `paperclip` gem provides this out of the box. – Harish Shetty Sep 21 '11 at 05:22
  • I think your specific problem might be addressed by the solution above. If you want to change the field name generically, then refer to this SO question http://stackoverflow.com/questions/2521383. – Harish Shetty Sep 21 '11 at 05:26
  • Maybe I was not clear. I do not want to change the error message text itself but the error-hash key during the validation process. I would like to do something better of the following in order to reach what I aim to do: `@user.errors.add(:avatar, @user.errors[:avatar_file_size].first) if @user.errors[:avatar_file_size].present?` – Backo Sep 21 '11 at 05:44