简体   繁体   English

Rails 3.1更改Controller中的URL

[英]Rails 3.1 Change the URL in a Controller

How do I Change the URL for the view in the controller. 如何更改控制器中视图的URL。
In my controller I generate an ID which I want to display 在我的控制器中,我生成了一个我想要显示的ID
in the URL of the browser when the view is rendered. 在呈现视图时在浏览器的URL中。

For example, when I enter / in my browser, it should redirect me 例如,当我进入/浏览器时,它应该重定向我
to /test/1. 到/ test / 1。 The ID is generated randomly by the controller. ID由控制器随机生成。
So when I access / the 2nd time it could redirect me to /test/3. 因此,当我访问/第二次它可以将我重定向到/ test / 3。

I tried to do a match route in my routes.rb file. 我试着在routes.rb文件中做一个匹配路由。
But I couldn't find a solution. 但我找不到解决方案。

routes.rb 的routes.rb

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

match '/test/:id', to: 'test#run'

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. 当然,您必须为Test模型编写random范围。 You may find helpful this question also - Random record in ActiveRecord 您可能会发现这个问题也很有用 - ActiveRecord中的随机记录

PS I'm not sure that the Test is a good name for your model. PS我不确定Test是否适合您的模型。 It could be already used by ruby or rails. 它可能已被ruby或rails使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM