Sam Ritchie
Sam Ritchie

Reputation: 11038

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?

Upvotes: 5

Views: 2605

Answers (2)

Unixmonkey
Unixmonkey

Reputation: 18784

# 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

Upvotes: 8

rtcoms
rtcoms

Reputation: 793

I have implemented functionality on similar line in my app. Will just give a brief description

In my app we have follow-unfollow functionality and user can invite his contacts from gmail, yahoo and facebook and by typing emails in text area .

If Email valid - no checkbox to send invite (invalid email message in front of that email)
If email valid and no user already registered using that - show checkbox to invite
If email valid and registered user - show follow unfollow button

I used contacts gem to fetch contacts from gmail and yahoo.

Rest of the coding you have to do it yourself, I don't think there is any gem available for that.

Upvotes: 0

Related Questions