Creating a rails route to an external URL

前端 未结 4 1382
一向
一向 2020-11-30 05:41

A lot of my users keep going to http://(rails app URL)/blog, but I don\'t actually have a blog. I finally setup a Posterous blog and now want to direct my users

相关标签:
4条回答
  • 2020-11-30 05:57

    Depends on the Rails version you are using.

    Rails 3

    # in routes.rb
    match "/blog" => redirect("http://example.com/blog"), :as => :blog
    

    Rails 2

    # in routes.rb
    map.blog '/blog',
      :controller => "a_helper_controller",
      :action => "redirect_to_blog"
    
    # in a_helper_controller.rb
    def redirect_to_blog
      redirect_to "http://example.com/blog"
    end
    
    0 讨论(0)
  • 2020-11-30 05:59

    For Rails 5:

    get '/stories', to: redirect('/articles')
    get '/stories', to: redirect('http://google.com')
    

    Rails Guide source page

    0 讨论(0)
  • 2020-11-30 06:04

    I know this is old, so in case someone else needs this for rails 4:

    get "/blog" => redirect("http://example.com/blog")
    

    Use get instead of Match in Rails 4, otherwise you'll get a Runtime error

    0 讨论(0)
  • 2020-11-30 06:08

    Emulate frontend routes as regular Rails controller routes

    Background : at the beginning there was Rails monolith rendering html view. Then came a frontend React app, and the need to convert the backend to a JSON api, and generate URLs (mostly in emails) pointing to a frontend app that behaves almost exactly like a Rails controller.

    I was looking for a way to mimick the rails resource way to construct URL but to point instead to a frontend URL and generate appropriate path_helpers, that could be used easily with my app, RSpec, cucumber/Capybara, and everything else. I found this hack around routes to emulate frontend routes, which also requires an extra param to be passed to completely desambiguate frontend VS backend routes (useful in capybara testing)

    frontend_scope = {
      as: :frontend,
      host: Rails.configuration.frontend_host, # like https://www.example.com
      port: Rails.configuration.frontend_port, # 443
      constraints: (lambda { |request| request.params[:app] == :frontend })
    }
    scope(frontend_scope) do
      root to: 'static_pages_controller#home'
      resources :articles, only: [:show, :index]
    end
    

    Then in my Ruby code I can use

    frontend_article_url(@article, app: :frontend)
    frontend_articles_url(app: :frontend)
    ... (and everything that can be generated in a classic rails app)
    

    The inconvenient is that there will be a app parameter in your redirection, that you would have to ignore on your frontend app + all other web apps like Google Analytics, Search engine, etc*.

    * the problem being, if you have both a /articles on your frontend and a /articles on your backend, your app will not be able to make the difference with both routes that resolve to the same URL without the help from an extra param

    0 讨论(0)
提交回复
热议问题