Syamsoul Azrien
Syamsoul Azrien

Reputation: 2742

Rails - route redirect based on Route Name

Currently, if I want to redirect to certain page, I must use to: redirect('/this-is-some-url') ..

I wondering if I can redirect to a certain page using Route Name such as to: redirect('route_name')

I try below code, but it's not working:

get '/house-url', to: redirect('home')          #the value is route name
get '/home-url', to: 'home_ctrl#show', as: 'home'

Upvotes: 1

Views: 1445

Answers (2)

Marthyn Olthof
Marthyn Olthof

Reputation: 1039

So if i read your question correctly you want to pass the requested route to a redirect?

You can do something like this:

get '/houses/:house_id', to: redirect { |path_params, req| "/houses/#{path_params[:house_id]}" }

Upvotes: 1

Xero
Xero

Reputation: 4175

You can redirect with the url path but not with the name of your route.

get '/house-url', to: redirect('/home-url')

Redirect any path to another path

https://guides.rubyonrails.org/routing.html#redirection

https://api.rubyonrails.org/classes/ActionDispatch/Routing/Redirection.html

Edit

I find a better way :

1. Create RedirectToHome

Create a class named RedirectToHome (in file redirect_to_home.rb).

You can create this for exemple in your app/controllers/

class RedirectToHome
  def call(params, request)
    Rails.application.routes.url_helpers.home_path # this is the path where to redirect
  end
end

2. Edit your route.rb

And add the RedirectToHome to your route that you want to redirect

  get '/home-url', to: 'home_ctrl#show', as: 'home'
  get '/house-url' => redirect(RedirectToHome.new)

Upvotes: 5

Related Questions