0

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

4

1 回答 1

1

您可以通过使用exists? . 它可能看起来像这样

email_exists = Invite.where(:email => params[:invite][:email]).exists?

# Create the new invitation if email not already used
if email_exists || Invite.new(params[:invite]).save
  @return = { :error => false, :response => "Thank you" }
else
  # error
  ...
end

或者您可以使用 arescue来捕获 ActiveRecord 异常

于 2012-07-25T16:49:36.597 回答