On 3.2
January 30, 2012 § 2 Comments
Last Rails 3.2 post. I swear.
I mentioned ActiveRecord::Relation#pluck
in a previous post because it was one I was particularly excited about. After reading through the rest of the release notes I wanted to highlight a few of the other smaller changes I thought were interesting.
ActiveRecord
ActiveRecord::Relation#uniq
Client.select('DISTINCT name')
is now written
Client.select(:name).uniq
You can also revert the uniqueness with
Client.select(:name).uniq.uniq(false)
Don’t user LOWER for case insensitive searches on MySQL
When querying against our databases there are a bunch of times we don’t care about case. In the case of searching against an email address, a case insensitive search does exactly what we want it to. When you add the :case_sensitive => true
to a validates_uniqueness_of
it use to wrap that part of the query in a LOWER()
. This sucked because it prevents MySQL from using an index. When you put this restriction on your email column and have to do this query every time you save a record. Since MySQL does case insensitive searches, ActiveRecord doesn’t worry about adding the LOWER()
around the columns. Time saved all around!
rake db:drop drops both dev and test
rake db:create
creates both the development and test databases. rake db:drop
now drops the both development and test databases instead of just the development database.
ActiveView
namespace form_for
When you have multiple forms on one page for the same type of objects, you can get conflicting ids form elements. Problem solved with form namespaces.
<%= form_for(@offer, :namespace => 'namespace') do |f| %> <%= f.label :version, 'Version' %>: <%= f.text_field :version %> <% end %>
The ids of the form elements have the namespace prepended with and underscore to the front of the original id.
ActiveSupport
Time Ranges
One of the things that I love most about Rails is ActiveSupport. And one of the things I love most about ActiveSupport is how it makes dealing with Time awesome and easy. They have added a few new convenience functions to help with date ranges:
Time#all_day
Time#all_week
Time#all_month
Time#all_quarter
Time#all_year
You can use these with ActiveRecord queries like so:
Event.where(:created_at => Time.now.all_week) Event.where(:created_at => Time.now.all_day)
Obviously there are a lot of other additions in 3.2, these are just the few that I know that I am going to have a use for. Enjoy.
Last one? Keep them coming!
Sammy, it’s the last one because there really isn’t anything else for me to say about it. There will be plenty more posts on other things though.