0

How do I Change the URL for the view in the controller.
In my controller I generate an ID which I want to display
in the URL of the browser when the view is rendered.

For example, when I enter / in my browser, it should redirect me
to /test/1. The ID is generated randomly by the controller.
So when I access / the 2nd time it could redirect me to /test/3.

I tried to do a match route in my routes.rb file.
But I couldn't find a solution.

routes.rb

get 'test/run'
root to: 'test#run'

match '/test/:id', to: 'test#run'
bekite
  • 3,444
  • 2
  • 23
  • 31

1 Answers1

2

How about that:

class TestController
  def show
    ...
  end

  def run
    redirect_to Test.random
  end
end

Of course, you have to write random scope for your Test model. You may find helpful this question also - Random record in ActiveRecord

P.S. I'm not sure that the Test is a good name for your model. It could be already used by ruby or rails.

Community
  • 1
  • 1
cutalion
  • 4,334
  • 1
  • 38
  • 47
  • I don't have a Test model. Test is only a controller that calls another model. But you answer helped me to improve my design. Is there no way to change the url from inside the controller? – bekite Dec 11 '11 at 17:57
  • It's possible with push state - https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history. Though it isn't supported by old versions of browsers. See how the github repository viewer works. – cutalion Dec 11 '11 at 18:11
  • Thank you. But I need a way to do this without the use of java script. – bekite Dec 11 '11 at 22:08