2013-04-10 127 views
0

我正在使用Rails创建基本产品登录页面,用户可以在其中输入他们的电子邮件地址,以便在产品启动时收到通知。 (是的,有服务/宝石等可以为我做这件事,但我是编程新手,并且想自己构建它来学习rails。)如何为表单确认页面定义自定义URL?

成功提交表单后,我想重定向到我感谢用户对产品的兴趣(并鼓励他们完成一项简短的调查)的定制“感谢”页面。

目前,成功提交显示在“/ invites /:id /”例如“邀请/ 3”,我不想要,因为它暴露了已提交的邀请数。我想将所有成功的提交重定向到“/谢谢”页面。

我试图研究“导轨自定义URL”,但一直未能找到任何有效的工具。我能找到的最接近的是Stackoverflow post on how to redirect with custom routes,但并未完全理解推荐的解决方案。我也尝试阅读Rails Guide on Routes,但对此我很陌生,没有看到任何我了解允许创建自定义URL的内容。

我已经把我想显示成功的形式提交的“意见/邀请/ show.html.haml”

我的routes文件

resources :invites 
root :to => 'invites#new' 

我想我的谢意消息插入routes.rb:

post "/:thanks" => "invites#show", :as => :thanks 

但我不知道这是否会工作,或者我会告诉控制器奥勒重定向到:感谢

我控制器(基本上香草轨,这里仅包括相关的动作):

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这似乎。任何意见如何实现这一点,将不胜感激。

回答

3

我想你想在创建操作后重定向,当表单提交时执行该操作。

只需通过以下方式添加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 

,并创建应用程序/视图/邀请一个thanks.html.erb页面。

+0

这工作!谢谢! – andersr 2013-04-10 20:29:54

0

您可以创建这样一个路径:

resources :invites do 
    collection do 
    get 'thanks' 
    end 
end 

这也将创建一个名为thanks_invites_path的路径帮手。

这将是在invites/thanks路径,但如果你希望它是在/thanks,你可能只是做贾森提到:

get "/thanks" => "invites#thanks", :as => :thanks

as部分将产生一个助手来访问该页面:thanks_path

您需要在名为thanks控制器一个多余的动作,并把你需要里面的任何信息,而你也将需要一个名为thanks.html.erb

既然你希望每个人都去那个页面后,成功一个附加视图提交,在你创建行动,你将有:

format.html { redirect_to thanks_invites_path}(或thanks_path),你选择什么都,当你的名字的路线,你可以用rake routes检查它,如果它的好,不管rake routes说,只是在添加_path结束。

0

我会做routes.rbget "/thanks" => "invites#thanks",然后在你的控制器补充一点:

def thanks 
end 

然后添加一个文件app/views/invites/thanks.html.erb与感谢信的内容。