OUR BLOG

Thoughts on development, design and the world we live in.



Rails 3: ActiveRecord

By sarah in Uncategorized. Posted on September 25th

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:
[code]
Person.where(:last_name => "Woo").order(:first_name)
Person.where(:last_name => "Woo").order(:first_name).limit(1)
[/code]

You can optionally specify ASC or DESC when calling order
[code]
Person.order("last_name DESC").limit(2)
[/code]

You can call these methods in any sequence
[code]
Person.order(:first_name).where(:last_name => "Woo")
Person.where(:last_name => "Woo").order("first_name")
[/code]

By sarah | Posted in Uncategorized | Tagged | Comments (0)

Post a Comment

Your email is never shared. Required fields are marked *

*
*