Rails路由问题:URL出现重复ID无法去除(接触Rails仅一周)
Rails路由URL重复ID问题解决办法
嗨,刚接触Rails一周就能自己捣鼓路由已经超棒啦!别担心,这个重复ID的问题很好解决,咱们一步步理清楚~
问题根源分析
你把edit_book路由定义在author的member块里,而member类型的路由本身就会自动带上作者的ID(也就是URL里第一个多余的98)。但你又在路由路径里手动写了:author_id,这就导致Rails把作者ID重复解析了一次,最终生成的URL里就出现了两个98。
修正方案一:用规范的嵌套路由(推荐)
Rails推荐用嵌套资源来处理这种关联关系,不需要手动写:author_id,而且结构更清晰。你可以把路由改成这样:
# 注意:Rails路由规范里资源名要用复数哦,所以是authors不是author resources :authors do # 把书籍的标准REST动作嵌套进来,指定控制器为author_books resources :books, controller: 'author_books', except: [:index, :create, :update, :destroy] # 保留你自定义的那几个动作 member do get '/books', to: 'author_books#index' post '/books', to: 'author_books#create' patch '/books', to: 'author_books#update' delete '/books', to: 'author_books#destroy' end end
之后生成编辑链接时,用Rails自动生成的路由辅助方法,传入作者和书籍对象即可:
<td><%= link_to '编辑', edit_author_book_path(@author, @book) %></td>
这样生成的URL会是符合REST规范的/authors/98/books/98/edit,不会有重复ID。
修正方案二:保留你想要的URL格式
如果你坚持要/author/:author_id/books/edit/:id这种URL结构,那只要把edit_book路由移出member块就可以了,避免重复的作者ID解析:
resources :authors do # 把edit路由放在member块外面 get 'books/edit/:id', to: 'author_books#edit', as: 'edit_book' # 其他动作保持你的配置 member do get '/books', to: 'author_books#index' post '/books', to: 'author_books#create' patch '/books', to: 'author_books#update' delete '/books', to: 'author_books#destroy' get '/books/new', to: 'author_books#new' end end
对应的链接写法不变,还是传入作者和书籍对象:
<td><%= link_to '编辑', edit_author_book_path(@author, @book) %></td>
这次生成的URL就是你想要的/authors/98/books/edit/98,不会出现多余的重复ID啦~
内容的提问来源于stack exchange,提问作者JimBob
相关产品推荐
相关产品推荐

