mercredi 9 mars 2016

RoR Devise - create related new object after User creation

I have been stuck on this problem for way too long now.

Using Devise for the first time, I am trying to combine new user sign up with the automatic joining of a group, based on the existence of an invitation token in the params. (E.g. Email invitation to join a group, so when they follow signup link and complete signup, they are automatically a member of the invited group)

Following tutorials, I have been able to customise the Devise controller, with the User being created successfully when an invitation token exists, however I cannot then use the ID from the new user object to create a group membership - the membership is created successfully, with group_id added, but the user_id always remains nil.

Below is my customised Devise controller, and relevant models:

class Users::RegistrationsController < Devise::RegistrationsController

    def create

        super do
            newUser = User.create(resource_params)
            token = params[:invite_token]

                      if token != nil
                         group = Invite.find_by_token(token).group          
                         newUser.groups.push(group)                         
                         Membership.create(:user_id => newUser.id, :group_id => group.id)
                      end
        end

    end

end



class Membership < ActiveRecord::Base
    belongs_to :user
    belongs_to :group
end


class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable

    has_many :memberships
    has_many :groups, :through => :memberships
    has_many :gifts
    has_many :posts
    has_many :votes
    has_many :invitations, :class_name => 'Invite', :foreign_key => 'recipient_id'
    has_many :sent_invites, :class_name => 'Invite', :foreign_key => 'sender_id' 
end


class Group < ActiveRecord::Base
    has_many :memberships
    has_many :users, :through => :memberships
    has_many :invites
    has_many :gifts
    has_many :posts
    has_one :user
end

Does anyone know how I might be able to successfully create the Membership object, containing both User_id and Group_id, after the User creation?

Thank you all in advance,

Aucun commentaire:

Enregistrer un commentaire