Search code examples
ruby-on-railscontrollerurl-routing

Creating a custom URL in Rails 5 Resource's show action


Given the resource Events, I want /events/1 to navigate to /events/1/column_name in the URL bar when entered. Column name is a t.string :name in the Events DB migration. This column_name will need parameterize to be called on it before redirecting. Any ideas on how to get this done?

Example:

If you navigate to https://stackoverflow.com/users/4180797 the URL will automatically become https://stackoverflow.com/users/4180797/james-lowrey after loading. Holds true for 4180797/any-other-txt-here. So "James Lowrey" would be the name column, and it would become james-lowrey after calling parameterize on it.


Solution

  • Ok this was really tricky to figure out, didn't even know I had access to a lot of these variables before.

    First edit your config/routes.rb to accept id/other_stuff

    Rails.application.routes.draw do
      resources :events
      get "/events/:id/*other" => "events#show" #if any txt is trailing id, also send this route to events#show
    end
    

    Next modify event_controller.show to redirect if the URL is incorrect.

      def show
        #redirect if :name is not seen in the URL
        if request.format.html? 
          name_param = @event.name.parameterize
          url = request.original_url
          id_end_indx = url.index(@event.id.to_s) + (@event.id.to_s).length + 1 #+1 for '/' character
          ##all URL txt after id does not match name.parameterize
          if url[id_end_indx..-1] != @event.name.parameterize
            redirect_to "/events/#{@event.id}/#{name_param}"
          end
        end
      end
    

    This will result in the exact same behavior as the Stack Overflow examples gave in the question.