Piggyback

An extension for piggybacking of ActiveRecord™ models.

What is Piggybacking?

Piggybacking refers to the technique of dynamically including attributes from an associated object into the master object. This is achieved by joining the associated object's table in a database query and selecting the attributes that should be included with the parent object.

This is best illustrated in an example. Consider these models:

class Author < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :author
end

ActiveRecord supports piggybacking simply by joining the associated table and selecting columns from it:

post = Post.joins(:author).select('posts.*, author.name AS author_name').first

post.title
# => "Why piggybacking in ActiveRecord is flawed"

post.author_name
# => "Alec Smart"

As you can see, the name attribute from Author is treated as if it were an attribute of Post. ActiveRecord dynamically determines a model's attributes from the result set returned by the database. Every column in the result set becomes an attribute of the instantiated ActiveRecord objects. Whether the columns originate from the model's own or from a foreign table doesn't make a difference.

Or so it seems. Actually there is a drawback which becomes obvious when we select non-string columns:

post = Post.joins(:author).select('posts.*, author.birthday AS author_birthday, author.rating AS author_rating').first

post.author_birthday
# => "2011-03-01"

post.author_rating
# => "4.5"

Any attributes originating from the authors table are treated as strings instead of being automatically type-casted as we would expect. The database returns result sets as plain text and ActiveRecord needs to obtain type information separately from the table schema in order to do its type-casting magic. Unfortunately, a model only knows about the columns types in its own table, so type-casting doesn't work with columns selected from foreign tables.

We could work around this by defining attribute reader methods in the Post model that implicitly convert the values:

class Post < ActiveRecord::Base
  belongs_to :author

  def author_birthday
    Date.parse(read_attribute(:author_birthday))
  end

  def author_rating
    read_attribute(:author_rating).to_f
  end
end

However this is tedious, error-prone and repetitive if you do it in many models. The type-casting code shown above isn't solid and would quickly become more complex in a real-life application. In its current state it won't handle nil values properly, for example.

Piggyback to the rescue!

Piggyback introduces the piggybacks directive which allows us to easily define which attributes we want to piggyback from associated models. Not only does it take care of the type-casting but also provides us with some additional benefits.

You simply declare which association you want to piggyback and how the attribute names should be mapped:

class Post < ActiveRecord::Base
  belongs_to :author

  piggybacks :author, :birthday => :author_birthday, :rating => :author_rating 
end

Now you can do the following:

post = Post.piggyback(:author).first

post.author_birthday
# => Tue, 01 Mar 2011

post.author_rating
# => 4.5

The type-casting works with any type of attribute, even with serialized ones.

As you can see, the piggibacks statement replaces the joins and select parts of the query. Using it is optional but makes life easier since you don't have to write the SQL for select by hand.

Of course, piggibacks plays nice with Arel and you can add additional joins, select and other statements as you like, for example:

Post.select('posts.title, posts.body').piggibacks(:author).joins(:comments).where(:published => true)

Please note: If you want to restrict the columns selected from the master table as in the example above, you have to do so before the piggibacks statement. Otherwise it will insert the select-all wildcard SELECT posts.* rendering your column selection useless.

If you don't need to map the attribute names of the piggybacked model, you can simply do:

piggyback :author, [:name, :birthday, :rating]

Computed values

If you want to use an SQL-expression for selecting an attribute, Piggyback can also help you with that. If Author didn't have a single name attribute, but first_name and last_name, you could concatenate them into a single attribute:

class Post < ActiveRecord::Base
  belongs_to :author

  piggybacks :author, :author_name => "authors.first_name || ' ' || authors.last_name" 
end

post.author_name
# => "Donald Duck"

In fact, every value you pass in as a string will be treated as raw SQL in the SELECT clause.