Rails 3: ActiveRecord

Rails 3 cheat sheet Part 2: ActiveRecord

Everything you know from Rails 2 still works and will for some time, but there is new cool stuff AND some of the Rails 2 syntax is deprecated and will eventually go away, so you should be aware.

1) Use first, last, all (not find(:first), find(:last) and find(:all)

2) New query syntax:
find(:conditions => …) will be deprecated, instead you can use the following methods:

  • where – provides conditions on the relation, what gets returned.
  • select – choose what attributes of the models you wish to have returned from the database.
  • group – groups the relation on the attribute supplied.
  • having – provides an expression limiting group relations (GROUP BY constraint).
  • includes – includes other relations pre-loaded.
  • order – orders the relation based on the expression supplied.
  • limit – limits the relation to the number of records specified.

For a complete list and more details, see Pratik Naik’s post. The key thing to note is that ActiveRecord finder methods return a relation and no SQL is executed until it needs to be.

Examples:

Person.where(:last_name => "Woo").order(:first_name)
Person.where(:last_name => "Woo").order(:first_name).limit(1)

You can optionally specify ASC or DESC when calling order

Person.order("last_name DESC").limit(2)

You can call these methods in any sequence

Person.order(:first_name).where(:last_name => "Woo")
Person.where(:last_name => "Woo").order("first_name")

Post a Comment

Your email is never shared. Required fields are marked *

*
*