简体   繁体   中英

How can I return error messages from SQL and use these error messages in my rails app?

I know unique: true makes a column unique in Ruby on Rails migration

add_index :table_name, :column_name, unique: true

I also know that validates:username, uniqueness: true makes a column unique too.

I wanna just to use add_index:table_name, :column_name, unique: true for making my specific column unique.

If I only use from add_index:table_name, :column_name, unique: true without validation in any model, how can I return error messages from SQL and use these error messages in my rails app?

eg
assume the email field is unique. and for making it unique, I just use add_index:table_name, :column_name, unique: true

User.create(name: "John", email: "john@gmail.com")
User.create(name: "Sofia", email: "john@gmail.com")    # it should returns an error

How can I get that error message and use it in my rails app?

To have uniqueness done right in Rails way you need to have validation in model and index in database.

Just add validates:name, uniqueness: true and you will be fine.

There could be still some rarely cases when you get SQL error message instead of ActiveRecord error because of race condition.

More info: https://guides.rubyonrails.org/active_record_validations.html#uniqueness

If you need to rescue duplicate errors raised by SQL you can use activerecord-rescue_from_duplicate gem. Using this gem allows whether use rails validation or not.

But generally speaking, adding uniqueness validation in your models doesn't guarantee uniqueness until you add a unique db index Check out this thread as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM