Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Project Invites in Rails

Hey all, I'm looking for a way to add an invitation strategy to my Rails app. I'm using Devise for authentication, and like the look of devise_invitable, but as far as I can tell, that gem only allows you to invite new users to the system.

In my app, a user has the ability to invite other users (using email) to join his current project. If that email address exists, the user is added; if the address doesn't exist, I'd like to send a project-specific invitation to that email address. If the user already has an account, she can log in and bind her account to that project. If not, she can create a new account.

Does anyone have any advice on where to look for such a system?

like image 683
Sam Ritchie Avatar asked Nov 30 '10 19:11

Sam Ritchie


1 Answers

# app/models/invite.rb
class Invitation < ActiveRecord::Base
  validates_uniqueness_of :email, :scope => :project_id
  belongs_to :project
  has_many :users
  after_save :email_invite_if_no_user

  private
    def email_invite_if_no_user
      unless User.find_by_email(email)
        UserMailer.send_invite(self).deliver
      end
    end
end

# config/routes.rb
resources :projects do
  resources :invites
end

# app/controllers/invites_controller.rb
class InvitesController < ActionController
  before_filter :get_project

  def new
    # render invite form
  end

  def create
    @invite = Invite.new(params[:invite])
    @invite.project_id = @project.id
    if @invite.save
      flash[:message] = "Successfully invited #{params[:invite][:email]}"
      redirect_to @project
    else
      flash[:error] = "Could not invite #{params[:invite][:email]}"
      render :new
    end
  end

  private
    def get_project
      @project = Project.find(params[:project_id])
    end 
end
like image 71
Unixmonkey Avatar answered Nov 16 '22 21:11

Unixmonkey