CopyAndPaste

random programming notes

ActiveRecord - Use Include to Optimize SQL Query Performance

Consider you have a model Post and a mode Comment, where a Post has multiple Comments. You DB has 10 Posts and 2000 Comments. Now you want to get the all Posts and all Comments. How many SQL is executed if you do the following?

1
2
3
4
posts = Post.all
posts.each do |p|
  p.comments
end

Rails execute 2010 SQL query for you. The code is easy to write, but not so fun to run on your webserver. Rails gets the id of the Post objects and use them in 2000 seperate SQL query to get their Comments. What about getting all the Comments all together when fetching the Post objects? The include method does exactly that. It tells Rails to run one additional SQL query to fetch all the Comments object after the SQL fetch a Post object. The code is as follow:

1
Post.all(:include => :comments)

And this piece of code runs 20 SQL query instead of 2010 in the previous version. Yet another nice little thing to distinguish between software engineers and programmers.

Test Fixtures Tricks

Often we have model classes using serialized data fields. This is how I write the YML fixture test data:

Test fixture YML example for serialized array, serialized hash, and datetime
1
2
3
4
5
one:
  id: 100
  some_hash_serialized: <%= { :profile_image_url => 'http://....png' }.to_yaml.inspect %>
  some_array_serialized: <%= [ 'hello', 'world' ].to_yaml.inspect %>
  some_datetime: <%= first_occurred_at: <%= 10.days.ago.to_s(:db) %>

RESTful API

Representational state transfer

  • transfer of representations of resources
  • HTTP is accidentally RESTful
  • use pre-existing, well-defined interface, minimize the addition of new appplication-specific features
  • stateless - server stores no client context. server can be stateful
  • cacheable

Uniform interface

  • identification of resources
  • manipulation of resources through these representations
  • self-descriptive messages, eg. tells how to parse using MIME
  • hypermedia as the enginer of application state