Rails路线堆叠在一起

时间:2014-04-13 20:16:02

标签: ruby-on-rails

我试图让网址看起来像这样。

localhost:3000/teams/teamname/playername/

我已经做到了,所以团队名称会在团队之后展示,但我不知道如何在那之后显示球员的名字。

  • 编辑 -

我已经让它工作但不完全按我想要的方式工作。

  get 'teams/:link/players' => 'players#index'
  get 'teams/:link/players/new' => 'players#new'
  get 'teams/:link/players/:link' => 'players#show'
  get 'teams/:link/players/:link/edit' => 'players#edit'

显示localhost:3000 / teams / teamname / players / playername /。 这是唯一可能的方式吗?

1 个答案:

答案 0 :(得分:1)

根据与OP的聊天讨论,

关联设置不正确:

更改

class Player < ActiveRecord::Base 
  has_one :team 
end

class Player < ActiveRecord::Base 
  belongs_to :team 
end

此外,通过以下方式生成迁移,在team_id表中添加了foreign_key players

rails g migration AddTeamIdToPlayers team:references

然后运行rake db:migrate

最后,在routes.rb

更改

get 'teams/:link/players/:link' => 'players#show' 
get 'teams/:link/players/:link/edit' => 'players#edit'

get 'teams/:teamname/:playername' => 'players#show', as: :show_player 
get 'teams/:teamname/:playername/edit' => 'players#edit', as: :edit_player

新路线可以访问: 例如:

<%= link_to "Player", show_player(@team.name, @player.name)

其中@team表示Team的实例,@player表示Player的实例。