开发者

Ruby on Rails: Devise: How to add "invite user to belong to model"?

I have a Group model that has many members (User models).

class Group < ActiveRecord::Base
    belongs_to :owner, :class_name => 'User'
    has_many :members, :through => :group_members, :class_name => 'User'
end

Th开发者_开发技巧e User model is using Devise. I need to add the ability for a User (Group Owner) to "invite" another User (who may or may not have a User record yet) to belong to the Group. How should I go about doing this? Has something like this already been built and packaged as a Gem?


Well, first action would be to find the user and then add him to the group of he exists. If he does not exist, do something like send an invite by email and put that invitation into a separate table, also belonging to the group. Then, if someone with that same email address signs up, put the new user directly into the group. In total: Add a new model named like "invited_user" which only has an email address row and belongs to the group model.

class InvitedUser < ActiveRecord:Base
   belongs_to :group
end

Create an invite action like this:

def invite_user
   user = User.find_by_email(params[:email])
   group = Group.find(params[:id])
   if user
     group.users << user
   else
     send_invite user.email
     group.invited_users << user
   end
 end

And finally you need to subclass Devise's registration controller, so you can override/add to the default action after a successful sign up. However, this part may not be reliable since I'm partly relying on Devise's documentation and did not try it out myself:

class RegistrationsController < Devise::RegistrationsController

  protected

  def def after_sign_up_path_for(resource)
    invited_user = InvitedUser.find_by_email(resource.email)
    if invited_user
      invited_user.group.users << resource
      invited_user.destroy
    end
    after_sign_in_path_for(resource)
  end
end

Or something like that. And you still need to implement the send_invite action, of course

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜