如何编写包含两个键的路径?

How to write a path that includes two keys?

我有两个模型,艺术家和歌曲。每个艺术家 has_many 首歌曲。我想为 url.

中包含歌曲和艺术家的歌曲编写路径

我的路线:get 'songs/:artist/:id' => 'songs#song', as: 'song'

例如,"John Lennon" 对 "Imagine" 的 url 将是 /songs/John%20Lennon/Imagine

那 url 工作正常。我想不通的是如何为它写一条路径。这些不起作用:

song_path(song: "Imagine", artist: "John Lennon")
song_path("John Lennon", "Imagine")

有人知道正确的语法吗?

您在使用 Rails 5 吗? resource_path 在 Rails 5 中被弃用。您仍然可以使用 link_to "song title", song_path(artist: "John Lennon", id: "Imagine")

此外,请注意您在选项 1 中传递了密钥 "song" 并使用 "id" 定义了路由。