Search code examples
ruby-on-railsapplicationcontroller

How to append URL param through controller?


In my Rails app I want to forward my users to their personal sign in page which is stored in a cookie :user_subdomain. So when a user goes to www.app.com/sign_in, s/he should be automatically forwarded to www.app.com/sign_in/mycompany.

How can this be achieved?

I would like to keep my sign_in_path helper method because it's sprinkled all over my app.

If I simply redirect the new action using redirect_to sign_in_path(:name => cookies[:user_subdomain]) I end up in a loop.

Thanks for any pointers.


# routes.rb:

get 'sign_in', :to => 'sessions#new'

 # sessions_controller.rb:

class SessionsController < ApplicationController

  def new
    params[:name] ||= cookies[:user_subdomain]
  end

  ...

end

Solution

  • Then the solution is easy. You do not need to redirect, you just need optional parameter for your routes.

    bound parameters

    # routes.rb:
    
    get 'sign_in(/:company_name)', :to => 'sessions#new'
    # This will allow
    # /sign_in
    # and
    # /sign_in/mycompany
    # Both will lead to same action and you can keep your helper
    
    
    
    # sessions_controller.rb:
    
    class SessionsController < ApplicationController
    
      def new
        params[:company_name] ||= cookies[:user_subdomain]
        # You logic here
      end
    
    ...
    
    end