controller function
def request_invite
if !request.xhr?
render_404
return
end
@invitation = Invite.new(params[:invite])
if @invitation.save
@return = { :error => false, :response => "Thank you" }
else
error_message = '<div class="error_message">' + @invitation.errors.full_messages.map {|error| "<p>#{error}</p>"}.join + "</div>"
@return = { :error => true, :response => error_message }
end
render :json => ActiveSupport::JSON.encode( @return )
end
model
class Invite < ActiveRecord::Base
validates :email, :presence => true, :uniqueness => true
validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
end
this will either save to the db and show a success msg or throw an error if exist…
i want to show the success msg even if the email already exist in the database so it wont show that the email has already been added
You can achieve this by using exists? . It may look like this
Or you could use a
rescueto catch the ActiveRecord exception