rails 6.1.4 -- ruby 2.6.7p197
我正在开发一个小应用程序。到目前为止,它有一个表单,当提交时,会转到controller#create
方法。当记录为created
时,发生redirect_to
到thank_you
的方法。redirect_to
不工作。它实际上是重定向到show
方法。我在"假设"。这是一个路由问题,但我不确定我做错了什么。
我可以用一些帮助来弄清楚为什么redirect_to
要去show
而不是thank_you
。
EDIT in response to suggestion by @Vishal Jain below:
I've tried these in the redirect_to:
redirect_to(living_muay_thai_survey_pain_points_thank_you_path)
redirect_to(living_muay_thai_survey_pain_points_thank_you_url)
They both still take me to the show action/view.
Controller:
class LivingMuayThai::SurveyPainPointsController < ApplicationController
layout "living_muay_thai"
def index
end
def new
@survey_pain_point = LivingMuayThai::SurveyPainPoint.new
end
def create
pain_point = LivingMuayThai::SurveyPainPoint.new(pain_point_params)
if pain_point.save
flash[:notice]="Your survey has been submitted"
redirect_to(action: "thank_you")
else
flash[:notice]="Sorry, your survey could not be saved."
render
end
end
def thank_you
end
def show
end
...
end
-----------------------------
Routes:
namespace :living_muay_thai do
resources :survey_pain_points do
collection do
get :search
post :search
end
end
end
get 'living_muay_thai/survey_pain_points/thank_you'
post 'living_muay_thai/survey_pain_points/thank_you'
...
routes in command line for thank_you and show.
living_muay_thai_survey_pain_points_thank_you GET /living_muay_thai/survey_pain_points/thank_you(.:format) living_muay_thai/survey_pain_points#thank_you
living_muay_thai_survey_pain_point GET /living_muay_thai/survey_pain_points/:id(.:format) living_muay_thai/survey_pain_points#show
我添加了thank_you动作和视图,这样用户就不会转到索引视图。他们不需要看所有的调查记录。我在namespace
和resources
之外添加了thank_you
的路由,因为我无法让它在这些内部工作。
我看到thank_you
路由是复数...pain_points...
和显示是单数...pain_point...
我试图使thank_you
路由单数,但这不起作用。
我做错了什么?
谢谢你的帮助。
我明白了。在盯着它看了一个小时,尝试了不同的方法后,我想起了几年前我读到的一些规则,即路线的顺序很重要:First one that fits the route needed is used (or similar)
。因此,我将thank_you
路由移动到命名空间块之前,只是为了尝试它…:
get 'living_muay_thai/survey_pain_points/thank_you'
namespace :living_muay_thai do
resources :survey_pain_points do
end
end
和哈! !,它现在工作正常。仍然不确定为什么show
被视为适合thank_you
行动,但我确信当我不思考它时它会出现在我身上。
感谢您的关注。