How do I change the mongoid error message to a custom message?

36 Views Asked by At

In my app I am offering the user to 'subscribe' to a topic. I want to be able to show a custom message if they already are subscribed.

I have a uniquness validation in my rails model using mongoid.

class Subscription
  include Mongoid::Document
  include Mongoid::Timestamps
  field :email, type: String
  field :confirmed, type: Mongoid::Boolean, default: false
  belongs_to :topic

  validates_uniqueness_of :email

end

In my controller I am evaluating a possible error message:

  def subscribe
    ...

    respond_to do |format|
      if @subscription.save
        ...
      else
        format.html { redirect_to topic_url(@topic), alert: "Subscription was not created. #{@subscription.errors.full_messages[0]}" }
        ...
      end
    end
  end

The error message that comes back through "@subscription.errors.full_messages[0]" is:

  • "Email has already been taken"

I would like to change this to a custom message, e.g. "You are already subscribed to this topic".

How do I change the mongoid error message? I could just search and replace the exact string but that does not seem very elegant to me.

1

There are 1 best solutions below

0
peresvetjke On

If you want to replace message completely try this approach:

# config/locales/en.yml
---
en:
  mongoid:
    errors:
      models:
        subscription:
          already_subscribed: You are already subscribed to this topic


# app/models/subscription
class Subscription
  include Mongoid::Document
  include Mongoid::Timestamps

  field :email, type: String
  field :confirmed, type: Mongoid::Boolean, default: false

  belongs_to :topic

  before_validation :validate_uniqueness

  def validate_uniqueness
    return if self.class.where(email: email).none?

    errors.add(:base, :already_subscribed)
  end
end

You can customise standard mongoid error messages:

# config/locales/en.yml
---
en:
  errors:
    messages:
      taken: "has already been magically taken"

But you should expect attributes name prefix in full error messages then.