← Back to Upcase

Using session[:auto_join] to auto join a user to a group


(Jon Castillo) #1

I’m having trouble successfully redirecting to join_groups controller and firing the create action

Routes.rb

  match "/auth/:provider" => redirect("http://#{DOMAIN_NAME}/auth/#{:provider}"), :as => :signin   
match '/auth/:provider/callback' => 'sessions#create'

view.html.erb

<a class="btn btn-large btn-info" href="<%= signin_path('twitter', group_id: @group.id, auto_join: 'y') %>">Login with Twitter</a>

Sessions controller

class SessionsController < ApplicationController
  def create
    auth = request.env["omniauth.auth"]
    user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
    session[:user_id] = user.id
    if params[:group_id].present?
      if params[:auto_join].present?
        session[:auto_join] = params[:auto_join]
        redirect_to group_path(params[:group_id])
      else
        redirect_to group_path(params[:group_id])
      end
    else
      redirect_to welcome_path, notice: "Signed in!"
    end
  end
end

Groups controller
There error is occurring during the redirect_to because I don’t think I can redirect a post route

class GroupsController < ApplicationController
  before_filter :find_group, :only => [:show, :edit, :update, :email]
  before_filter :check_permission, :only => [:show]
  
  def show
    if session[:auto_join] == "y"
      **redirect_to join_groups_create_path**
    end   
  end

  def join
    @group = Group.find_by_token(params[:token])
    if current_user && current_user.member?(@group)
      redirect_to group_path(@group)
    end
  end
  
  private
  
    def find_group
      if params[:group_id]
        @group = Group.find(params[:group_id])
      else
        @group = Group.find(params[:id])
      end
    end
    
    def check_permission
      if current_user.nil?
        redirect_to root_path 
      end
    end
end

join_groups_controller

class JoinGroupsController < ApplicationController
  def create
    @group = Group.find(params[:id])
    current_user.memberships.create(group_id: @group.id, user_id: current_user.id)
    redirect_to group_path(@group.id)
  end
end

How do I successfully fire the #create in join_groups_controller?


(Chad Pytel) #2

@castillo you’re going to run into trouble, like you’ve found - and its not really best practice to have controllers causing create actions on other controllers.

You can have the session controller add the person to the group once they’ve successfully authenticated.
If you don’t want to introduce duplication into how a user should be joined to a group (which generally you don’t), you can push this functionality into the model layer of your application.

Let me know if thats clear, you have further questions, or have any other ideas, thanks very much,
-Chad