Tag Archive: devise: Social Memory Complex

Embedding users in accounts with Devise and Mongoid

This gist referred to by the Devise wiki is no longer accurate as far as I can tell. So I wanted to share my approach for how to use devise in a situation where user documents are embedded in account documents, especially in the scenario where your account has a subdomain assigned to it.

Obviously, the first thing you need to do is make sure you always have access to the current account as keyed by the subdomain. This means a before filter on any controller that runs under the subdomain that loads in your account. The idea is that once you load the account, you never have to pull it from the database again:

class AccountSubdomainController < ApplicationController
  before_filter :current_account

protected
  def current_account
    @account ||= params[:current_account] ||= get_account_by_subdomain
    params[:user][:current_account] = @account if params[:user]
    @account
  end

  def get_account_by_subdomain
    Account.where(:subdomain => request.subdomain.downcase).first
  end
end

If you're not using an account-specific subdomain, just modify this to pull out the account from the URL or something.

Read more...

Written on Friday, January 04, 2013
Tags: ruby, rails, devise, mongodb, mongoid
Comments