Lorena Bento
Lorena Bento

Reputation: 554

"Error": errors.add don't show only the message in locales/xx.yml

I have a method in the model is to check if one is suspicious attachment before to make the upload , in case , if his ends with . Bat . With . Exe , . Src or. Cmd .

I want to show a message if his file is suspicious . I'm portuguese , so I use one file of translate .

The method is:

def suspicious_attachment
  if ends_with? '.bat', '.com', '.exe', '.src', '.cmd'
    errors.add(:attachment_file_name, I18n.t('errors.messages.suspicious_attachment', :value => attachment.path[-4..-1]))
    errors.add_to_base(I18n.t('errors.messages.suspicious_attachment', :value => attachment.path[-4..-1]))
    errors.add(:attachment_file_name)
  end
end

Which returns :

Attachments attachment file name is not allowed to upload . With Attachments attachment file name is not valid Attachments base is not allowed to upload . With

I do not want to show Those words : "Attachments attachment file name" and "Attachments base ."

I do not understand why these words appear.

Sorry for my english.

Thanks

Upvotes: 2

Views: 1062

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

These extra string are displayed because you added an error message on attributes, not to the base:

errors.add(:base, "some custom error message")

will display a message like:

"some custom error message"

Whereas this

errors.add(:attribute, "other message")

will display a message like:

"attribute" other message"


In your case, use the :base to add your errors:

def suspitious_attachment
  if ends_with? '.bat', '.com', '.exe', '.src', '.cmd'
    errors.add(:base, I18n.t('errors.messages.suspitious_attachment', :value => attachment.path[-4..-1]))
  end
end

Or if you want to translate the attribute with the message:

activerecords:
  attributes:
    your_model_name:
      attachment_file_name: "File"

And use this to add the corresponding message:

def suspitious_attachment
  if ends_with? '.bat', '.com', '.exe', '.src', '.cmd'
    errors.add(:attachment_file_name, I18n.t('errors.messages.suspitious_attachment', :value => attachment.path[-4..-1]))
  end
end

Which should display an error like this:

"File" is not allowed to upload

Upvotes: 4

Related Questions