views:

142

answers:

1

Rails 3 newbie here.... I'm looking to build an application that limits a user's viewable data to their company, which is based on their email's domain. Very much like Yammer or basecamp. I'm currently using devise for auth...

I'd like a User's table and then a UserInstance Table... The UserInstance table would look like:

ID | domain 
 1 | yahoo.com 
 2 | github.com 
 3 | abc.com

I'd like for the each record in the user table to have an InstanceID that has an ID from the UserInstance table. During registration the UserInstance is either found or assigned (unique).... Then, all records in the DB would have an InstanceID. Now that all users are assigned to an instanceID... I'd like everything the signed in user sees in the site to only be for their InstanceID, so company's information is silo'd.

Question: 1. How to modify devise to support the UserInstance table, to assigned or create and then assigned instanceID on registration

So far I'm here, /app/models/user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :email, :password, :password_confirmation, :remember_me

    after_create :assign_user_to_instance

    def assign_user_to_instance
        logger.debug "Called after the account was created"
    end

end

What I'd like to see happen in assign_user_to_instance is as follows:

def assign_user_to_instance
 Step 1, extract the user's domain from the email address they just registered with
 Step 2, does this domain from s1 exist in the UserInstance Table (domain)?
 Step 2b, if not create it and grab the UserInstance.ID
 Step 2c, if it does, grab the already available UserInstanceID
 Step 3, assign the UserInstanceID to the user's record in the user table
end

Any help implementing the pseudo code above would be greatly appreciated.

Thanks!

+1  A: 

User model:

class User < ActiveRecord::Base
  # devise stuff
  belongs_to :instance, :class => 'UserInstance'
  def assign_user_to_instance
    domain = email.split("@").last
    user_instance = UserInstance.find_or_create_by_domain domain
    update_attribute(:instance_id, user_instance.id) #or whatever you called this field
  end
end

and you need a migration like this:

> rails g migration AddUserInstanceToUser

The migration should look like this:

class AddUserInstanceToUser < ActiveRecord::Migration
  self.up
    add_column :users, :instance_id, :integer
  end
  self.down
    remove_column :users, :instance_id
  end
end
jigfox
This is nice! Thank you. Any suggestions on how to update my devise user table? Do I add a migration that adds an instance_id column, or is there a belong_to type approach that does this relationship automatically?
AnApprentice
See my updated answer
jigfox
Thanks, this is awesome
AnApprentice