Search code examples
ruby-on-railsrails-routing

Rails routing for daily exercise


So right now I have a model called exercise and response. In my route, I have

resources :exercise, param: :title do
    resources :response
end

I'm trying to rewrite the url so that when users visit /daily-exercise, it will bring up the same view used for /exercise/:title/responses/new but the url on the browser will still be /daily-exercise. Does anyone know a way to do this?

EDIT: I forgot to mention this but the exercise changes everyday so I would have to map the url to a different action such as exercises#daily_exercise


Solution


  • Create a new custom route that maps to your #show action in the exercises controller:

    get '/daily-excercise', to: ' responses#show'
    

    The problem is you need a way to pull in the parameter for the excercise of the day. You could set this programmatically and ignore pull in an ID if it's on a daily basis in your controller.

    before_filter :define_exercise, only: :new
    
    def define_exercise
      if request.fullpath.match(/daily-exercise/)
        @excercise = Excercise.find_by_exercise 
      else
        @exercise.find(params[:title])
      end
    end
    

    As was mentioned, if you need to pass in the id as a param:

    get '/:title/daily-excersise', to: 'responses#show'
    

    Conversely, create another controller action #daily_exercise, but this isn't very RESTful.

    http://guides.rubyonrails.org/routing.html#singular-resources