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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With