Rails 6添加PodcastsController的show动作后Devise相关链接报错求解
问题根因
Rails路由匹配遵循从上到下优先匹配规则,你当前的路由配置里把resources :podcasts放在了devise_for :podcasts前面,所有/podcasts/xxx格式的请求都会优先匹配到podcasts#show动作,把sign_up、sign_in这类devise路径标识当成了podcast的id参数去数据库查询,自然就触发了RecordNotFound报错。
解决方案
第一步:调整路由顺序
把devise_for :podcasts移到resources :podcasts前面,修改后的路由配置如下:
Rails.application.routes.draw do devise_for :podcasts resources :podcasts, only: [:index, :show] root 'welcome#index' end
修改后devise的相关路由会优先匹配,不会再被podcasts的show路由拦截。
第二步:清理控制器冗余代码
你当前的PodcastsController里已经通过before_action :find_podcast为show动作提前查询了@podcast对象,show动作里的重复查询可以删掉,修改后的控制器代码如下:
class PodcastsController < ApplicationController before_action :find_podcast, only: [:show] def index @podcasts = Podcast.all.order("created_at DESC") end def show # 此处无需重复查询,before_action已完成@podcast赋值 end private def find_podcast if params[:id].nil? @podcast = current_podcast else @podcast = Podcast.find(params[:id]) end end end
修改完成后重启服务即可正常访问注册、登录等devise相关路径。
内容的提问来源于stack exchange,提问作者Kivindyo
相关产品推荐
相关产品推荐

