This document discusses using MongoDB and a relational database together in applications. It suggests testing your data and access patterns to determine if MongoDB is a good fit for parts of your app. If so, utilities, logging, comments, and isolated subsystems are examples of good candidates for MongoDB. The document provides instructions for setting up MongoDB with Rails applications using MongoMapper and ActiveRecord together. It also describes some challenges like replacing migrations and tool upgrades over time.
40. apps/models/user.rb
class User < ActiveRecord::Base
after_save :save_prefs
def preferences
@preferences ||= Preferences.find_or_create_by_user_id(id)
end
private
def save_prefs
@preferences.save if @preferences
end
end
41. Usage
# Set any preferences you like
user = User.find_by_login('thatguy')
user.preferences[:foreground] = '#FF0000'
user.preferences[:foo] = 'bar'
user.save
# Later on, you can do this
user = User.find_by_login('thatguy')
user.preferences[:foreground] #returns '#FF0000'
44. Any attribute, any time
# Grab a user
user = User.find(1)
# Now set an attribute that didn't exist before
user.expandos.foreground = '#FF0000'
# foreground is saved in Mongo
user.save
# Find any users with a red foreground color
users = User.expando_all(
:conditions=>{:foreground=>'#FF0000'}
)
45. Skip expandos, use delegate
class Post < ActiveRecord::Base
expando_config do
delegate :tags
end
end
p = Post.find(1)
p.tags = ['foo','bar']
p.save
# Find any Post with the tag "foo"
Post.expando_all(:conditions=>{'tags'=>'foo'})