Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle ActiveRecord::RecordNotUnique in Rails properly

I am trying to enforce uniqueness with unique index in my Rails project. And I found something confusing.

Like registering a user at my site, you need to provide an email address and a nickname, both need to be unique. I add unique index to both email and nickname. And when duplications come, I rescue exception ActiveRecord::RecordNotUnique, now here's the question, how could I know which field cause the exception?

Thanks a lot for the help.

like image 814
larryzhao Avatar asked May 10 '15 11:05

larryzhao


People also ask

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What's the purpose of ActiveRecord?

Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

Is ActiveRecord part of rails?

Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

What are ActiveRecord methods?

This method returns an array of column objects that Active Record considers the actual con- tent, or data, of the Active Record class. Therefore, this array does not include the primary ID column, any columns ending in _id or _count, and any columns used for single table inheritance.


1 Answers

IMHO you should also add uniqueness validators to your model. That allows you to use Rails' validations and error messages.

# add to model
validates :email,    uniqueness: true
validates :nickname, uniqueness: true

Note that to ensure uniqueness on a database level a unique index is still needed.

like image 196
spickermann Avatar answered Sep 28 '22 10:09

spickermann