Saturday, January 24, 2015

This week in Rails: model error details, drop table if exists and more!

Posted by claudiob

It’s Friday! Gotta get down on This Week in Rails!

This is Claudio, rushing to get you the weekly updates on interesting commits and pull requests from Rails.

This week’s Rails contributors

25 contributors helped Rails become a better framework. Keep the patches coming, and Rails 5 will be ready before you know it.

New Stuff

ActiveModel::Errors#details

Given a user without an email, user.errors.details will return {email: [{error: :blank}]}. In some cases, this is more useful than the message {email: ["can't be blank"]} provided by user.errors.messages.
There’s a good usage example in this blog post.

:if_exists option for drop_table

Writing drop_table(:users, if_exists: true) in a migration ensures that the migration will run without exceptions, whether or not the “users” table exists.

ActionController::Renderer

The ActionController::Base#render method can now output a template anywhere, even outside of a controller!

ActiveRecord::Base#accessed_fields

Calling @users = User.all to list all users works, but you can get better performance by indicating the exact fields you intend to access, for instance with @users = User.select(:name, :email).

The new @users.accessed_fields method will give you the list of fields accessed from the model, so you can easily optimize your queries using .select rather than .all.

Improved

Speed up ActionController::Renderer

Everyone loves a pull request that speeds up Rails, especially if the performance gain is documented and verifiable.
When in doubt, always use benchmark/ips to provide benchmark results for comparison.

Wrapping up

That’s all for This week in Rails. As always, there are more changes than we have room to cover here, but feel free to check them out yourself!

P.S. If you enjoyed this newsletter, why not share it with your friends? :) If you wish to be part of this project please don’t hesitate to contact Godfrey – there’re a lot of ways you could help make this newsletter more awesome!