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.
If you want to replace message completely try this approach:
You can customise standard mongoid error messages:
But you should expect attributes name prefix in full error messages then.