2012-04-22 82 views
0

重定向如何在rails中工作?我觉得它非常直观和令人沮丧。下/views/mymodels/custom.html.erbRails 3重定向

我已经添加视图文件我已经清空控制器的方法:

def custom 

end 

我有以下的routes.rb中:

resources :mymodel do 
    member do 
     get 'custom' 
    end 
    end 

在我的控制器中我尝试呈现模型创建时的自定义视图:

respond_to do |format| 
    if @presentation.save 
    redirect_to action: "custom" 
    #format.html { redirect_to @mymodel, notice: 'Presentation was successfully created.'} 
    #format.json { render json: @mymodel, status: :created, location: @mymodel } 

这会导致重定向呈现空白页面。但浏览/mymodels/[id]/custom工作正常。我究竟做错了什么?为什么render :action => "custom"也无法工作?

编辑:

这工作:format.html { render action: "upload" }但为什么呢?

回答

2

为什么评论format.html {...}条款?使用方法:

代替:

if @presentation.save 
    redirect_to action: "custom" 
    #format.html { redirect_to @mymodel, notice: 'Presentation was successfully created.'} 

这样写:

if @presentation.save 
    format.html { redirect_to action: "custom" } 
+0

为什么没有普通redirect_to的工作? – Fdr 2012-04-22 11:00:56

+0

因为你将它放在'respond_to'块中。注释该块并将'redirect_to'移到其外面并检查。所有人都应该像你期望的那样工作。 – jdoe 2012-04-22 11:16:49

+1

但是你必须认识到,这种从'respond_to'移出的过程只能是为了好玩,不能再有。在真实世界的应用程序中,您有义务使用响应程序 - 它是可读的,它是一个RESTful,它是一种MVC兼容方法,用于在各种表示形式中显示单个资源。通过这种方式,您可以轻松扩展您的产品,用于以json/xml/other格式进行表示,而无需添加新操作,更改路由和其他内容。 – jdoe 2012-04-22 12:46:46