Rails 5 ActiveRecord Changes

Rails 5 ActiveRecord Changes


You Won't Believe These 7 Insane Changes in Rails 5 ActiveRecord!

Just when you were feeling like a level 11 wizard with Rails 4 somebody had to go and change it all up. Actually there are some pretty cool changes coming... in the next few weeks? Months? I don't know, but change has a way of coming sooner than you think. The time is ripe for preparation. What's that? You're still running your app on Rails 2.3? Well shitsticks. Let's just continue, shall we?


Not to be confused with those Chinese stocks you bought that are now depreciating thanks to the yuan devaluation. What is this MSNBC? Rails, we are talking about Rails Jeremy! Focus.

First off, there are two gems that are no longer supported in Rails 5:

  • protected_attributes
  • activerecord-deprecated_finders
Deprecating the deprecated finders gem? Mmm, tastes like delicious irony.


New Features

#or method for ActiveRecord::Relation class

This allows us to write database queries with Ruby syntax like:
User.where(name: 'Jon').or(User.where(name: 'John'))
that would previously need to be written using SQL syntax:
User.where('name = ? OR ?', 'Jon', 'John')

#belongs_to relationship is required by default

If you have two models like Comment and User, and a comment belongs_to :user, a validation error will be triggered if you try to save an instance of a model and the relationship isn't there. A flag for optional: true can be added if this default behavior isn't desired.


ActiveRecord attribute types can be overridden when desired

This lets you modify/convert the type of value from whatever is stored in the database to what you want to use in your models. For example, a database may store an extremely precise number of cents or an average number of people in a household. You can then set up your model to translate those to whole numbers so instead of 99.99 cents you have 100 cents, or instead of 2.05 children you have 2 children. There are just some things you don't want a fraction of.


has_secure_token for token attributes on a model

This can be used to generate a secure token for a password reset for example.


JSON support for ActiveRecord adapter

Rails apps using MySQL 5.7.8 will have access to a native JSON data type. This means you can store JSON in your database and have direct access to it through Rails ActiveRecord models. Nice.

All in all some pretty interesting changes are coming with the Rails 5 release. I don't know about you, but I for one look forward to our new Rails 5 Overlords.

PS - Need help updating your Rails app or building a new one?

Hit up the 'Get in Touch!' section over in the right column ➡
Jeremy Clemans
Jeremy Clemans