问题描述
我正在使用 Rails 创建一个基本的产品登录页面,用户可以在其中输入他们的电子邮件地址,以便在产品发布时收到通知.(是的,有服务/宝石等可以为我做这件事,但我是编程新手,想自己构建它来学习 Rails.)
成功提交表单后,我想重定向到自定义"/感谢"页面,在该页面中我感谢用户对产品的兴趣(并鼓励他们完成一个简短的调查.)
目前,成功的提交会显示在"/invites/:id/",例如"invites/3",这是我不想要的,因为它公开了已提交的邀请数量.我想将所有成功的提交重定向到"/thanks"页面.
我曾尝试研究"rails 自定义 URL",但找不到任何可行的方法.我能找到的最接近的是 Stackoverflow 上的帖子如何使用自定义路由重定向,但不完全理解推荐的解决方案.我也尝试阅读 Rails Guide on Routes,但对此我很陌生,没有看到任何内容我理解允许创建自定义 URL.
我已将我希望在"views/invites/show.html.haml"中成功提交的表单上显示的感谢信息
我的路线文件
resources :invites root :to => 'invites#new'
我尝试在 routes.rb 中插入:
post "/:thanks" => "invites#show", :as => :thanks
但我不知道这是否可行,也不知道如何告诉控制器重定向到:谢谢
我的控制器(基本上是 vanilla rails,这里只包含相关操作):
def show @invite = Invite.find(params[:id]) show_path = "/thanks" respond_to do |format| format.html # show.html.erb format.json { render json: @invite } end end # GET /invites/new # GET /invites/new.json def new @invite = Invite.new respond_to do |format| format.html # new.html.erb format.json { render json: @invite } end end # POST /invites # POST /invites.json def create @invite = Invite.new(params[:invite]) respond_to do |format| if @invite.save format.html { redirect_to @invite } #format.js { render :action => 'create_success' } format.json { render json: @invite, status: :created, location: @invite } else format.html { render action: "new" } #format.js { render :action => 'create_fail' } format.json { render json: @invite.errors, status: :unprocessable_entity } end end end
似乎创建一个用于显示确认的标准 URL 会相对简单.任何有关如何实现这一目标的建议将不胜感激.
推荐答案
我猜你想在你的创建动作之后重定向,它在表单提交时执行.
只需按以下方式添加redirect_to即可:
def create @invite = Invite.new(params[:invite]) if @invite.save ... redirect_to '/thanks' else ... redirect_to new_invite_path # if you want to return to the form submission page on error end end
为了简洁,我省略了一些代码.
在您的路线中添加:
get '/thanks', to: "invites#thanks"
将感谢操作添加到您的邀请控制器:
def thanks # something here if needed end
并在 app/views/invites 中创建一个 Thanks.html.erb 页面.