TIL some awesome ActiveRecord behaviors in Rails

So I started using rails about 3 months ago and it has been awesome. ActiveRecords was my first experience using ORM. I wish I had started using this a long time ago since using associations makes life so easy.

As you read tutorials, there are many things that are left out. And unless you find them by doing an unrelated search, it is hard to know what else you could be using. This is the case for me with ActiveRecord associations, there are many things that I have learned because I was looking for something and found some nice feature that someone else was having issues with.

For example this is what I learned today. Lets take the following Models:

class Account < ActiveRecord::Base
  has_many :contacts
  accepts_nested_attibutes_for :contacts
end
class Contact < ActiveRecord::Base
  belongs_to :account
end

First I learned that I can do a search of contacts directly from the @account instance var, so if I am in the account#show view and I want to display all the contacts that contain "Manage" in the title, I can do this:

  managers = @account.contacts.where(:title => "manager")

You can get all the contacts for that account

  all = @account.contacts

You can just iterate over the list without assigning it

  @account.contacts.each do |contact|
   do something
  end

This also works backwards. Lets say you are iterating over all the contacts in your contacts#index view and you want to create a link back to the account the contact belongs to. You can easily do that by doing this:

  <% @contacts.each do |contact| %>
    some styling stuff....

    <%= lint_to contact.account.name, account_path(contact.account.id) %>

    some other styling stuff....
  <% end %>

I wish someone had explained to me earlier how stuff like that works, I think it is just so very useful and should be at the top of any tutorial talking about ActiveRecord Associations

1 Comment


  1. This is really the great thing about ORMs. You don’t want your objects to have to have properties that your business layer needs to know about, like Ids. Instead of your business layer getting the Id of one object and then doing a query to the database with that Id, your business layer should just be able to use a property on the main object that returns an object (like account.contacts). The first way, passing Ids around like we used to do in the good ol’ PHP days at Shutterbug, is just plumbing that the business layer shouldn’t have to care about.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.