Nazeef Ahmad Meer
Nazeef Ahmad Meer

Reputation: 113

ActiveRecord raising exception on save without a bang in Rails

I have this code in my controller :

 @user = User.new(params.require(:user).permit(:email,:password))
    if @user.save
      redirect_to(home_users_path, :notice => "Success")
    else
      redirect_to(new_user_path , :notice => 'Signup Failed.')
    end

but I am getting ActiveRecord::RecordNotUnique in UsersController#create.

I know the record is not unique, my question is I am using .save which should not generate any exception but return false. But in my application .save is behaving as save!

Upvotes: 2

Views: 2401

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

Indeed, when you have validates :status, uniqueness: true in the model , save! will raise an exception, but save won't.

But ActiveRecord::RecordNotUnique is raised, because there's a uniqueness index on the column, so the validation is performed on database level. Just like ActiveRecord::RecordNotFound, when find method is called, though find is not a bang-method

Upvotes: 3

Related Questions