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
Leave a Reply