The following blog post contains material either currently found or soon to be incorporated into my new book, "Easy Active Record for Rails Developers". Among many other topics, you'll learn about model generation, migrations, validations, associations, scopes, joins, includes, forms integration, nested forms, and model testing with RSpec and FactoryGirl. The book is now available, head over to this website's home page to learn more.


The following blog post is adapted from material presented in my new book, “Easy Active Record for Rails Developers”. Among many other topics, you’ll learn about model generation, migrations, validations, associations, joins, includes, forms integration, nested forms, and model testing with RSpec and FactoryGirl. The book is slated for release in early June. The book is now available, head over to this website’s home page to learn more.


Following retrieval of a collection of Active Record objects you may wish to subsequently push some of the data into a hash for further processing. For instance, suppose you were selectively managing commonly used Twitter hashtags alongside arcade game location names, using those hashtags in conjunction with the Twitter API to mine data about those locations. The schema might look like this:

CREATE TABLE locations (
  id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  tweet_hash VARCHAR(255) NOT NULL DEFAULT ''
);

You could retrieve a collection of Location objects which have a hashtag associated with them using the following query:

locations = Location.where('tweet_hash != ""')

Converting the retrieved data into a hash can be accomplished in a variety of ways, some more clever than others. Perhaps the most rudimentary way involves simply looping over locations and adding the desired attributes to a hash:

tweet_hashes = {}
locations.each do |t|
  tweet_hashes[t.id] = '#' + t.tweet_hash
end

This produces a hash which looks like this:

{584=>"#BW3s", 615=>"#RedRoofWed"}

If you’d like to eliminate the loop, you can use the following construct (Ruby 1.8.7+):

tweet_hashes = {}
tweet_hashes = Hash[ tweet_hashes.map{ |t| [t.id, '#' + t.tweet_hash] } ]

This variant produces the same hash as above:

{584=>"#BW3s", 615=>"#RedRoofWed"}

Like what you read? There’s plenty more where this came from in my new book, “Easy Active Record for Rails Developers”!

Comments