如何在rails 4中获取自定义URL

时间:2015-04-07 11:10:53

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-4.2

我用scaffold创建了rails项目 http://localhost:3000/games/

当我添加新游戏时,我会获得网址 http://localhost:3000/games/first-game

我想将此更改为 http://localhost:3000/game/first-game 要么 http://localhost:3000/first-game

我的路线文件有

resources :games

3 个答案:

答案 0 :(得分:1)

如果您希望资源games充当根路径,您可以将其设置为' /'在 routes.rb

resources :games, path: '/'

如果您只想进行show操作(正如我想的那样),请使用:

resources :games, path: '/', only: [:show]
resources :games, except: [:show]

(这将给出http://localhost:3000/first-game

或者第三,避免冲突路线可能是最明智的,使用单数游戏调用show动作'路径:

resources :games, path: 'game', only: [:show]
resources :games, except: [:show]

(这将给出http://localhost:3000/game/first-game

答案 1 :(得分:0)

您可以为此操作创建自定义路线:

get '/games/first-game' => 'Games#first_game'

答案 2 :(得分:0)

你可以这样做:

resources :games
  member do
    get 'first-game', to: 'games#first_game', as: :first_game
  end
end

阅读Naming Routes指南。