2013-02-11 54 views
4

Rails项目:Project有很多Ticket's。RoR:更新操作。渲染路径时出现错误

路径编辑票:/projects/12/tickets/11/edit

当更新票和验证失败,我用render :action => "edit"

然而,当编辑视图渲染这段时间,路径改变为/tickets/11/

这意味着我失去了一些参数。我怎样才能保持原来的道路?

的routes.rb:

resources :projects do 
    resources :tickets 
    end 
    resources :tickets 

tickets_controller.rb

def new 
    @ticket = Ticket.new 
    end 

    def create 
    @ticket = Ticket.new(params[:ticket]) 
    @ticket.user_id = session[:user_id] 

    respond_to do |format| 
     if @ticket.save 
     format.html { redirect_to project_path(@ticket.project), :notice => "Ticket was created." } 
     else 
     format.html { render :action => "new" } 
     end 
    end 
    end 

    def edit 
    @ticket = Ticket.find(params[:id]) 
    end 

    def update 
    @ticket = Ticket.find(params[:id]) 
    respond_to do |format| 
     if @ticket.update_attributes(params[:ticket]) 
     format.html { redirect_to project_ticket_path(@ticket.project, @ticket), :notice => "Ticket was updated." } 
     else 
     format.html { render :action => "edit" } 
     end 
    end 
    end 
+0

我们可以看看你的'routes.rb'吗? – gabrielhilal 2013-02-11 12:27:16

+0

更新了问题。 – user1121487 2013-02-11 12:29:45

回答

1

您呼叫资源的两倍。如果您不想“丢失一些参数”,请删除第二个参数。

resources :projects do 
    resources :tickets 
end 

但是,如果你想拥有resources :tickets非嵌套的,以及,你可以将它限制为仅showindex避免创建和编辑时丢失了一些参数。

resources :projects do 
    resources :tickets 
end 
resources :tickets, :only => [:index, :show] 

编辑 - 我认为这个问题是在你的形式比。
请确保您有两个对象:

form_for([@project, @ticket]) do |f| 

此外,您必须在创建或更新ticket之前找到project。所以,你的newedit行动必须有类似:

@project = Project.find(params[:project_id]) 
@ticket = @project.ticket.build 

与同为create行动:

@project = Project.find(params[:project_id]) 
@ticket = @project.ticket.build(params[:ticket]) 

EDIT2 - 你的更新动作应该是这样的:

@project = Project.find(params[:project_id]) 
@ticket = Ticket.find(params[:id]) 
if @ticket.update_attributes(params[:ticket]) 
... 
+0

我试过了,但是当试图更新票时,这给了我错误页面:没有路由匹配[PUT]“/ tickets/10” – user1121487 2013-02-11 12:38:28

+0

好的,我已经添加了:url => {:action =>“update “}在我的form_for中,在视图中。现在它可以工作。但是,我使用该表单作为部分视图,也用于创建。猜猜无法完成? – user1121487 2013-02-11 12:43:17

+0

我编辑了答案,您可以使用相同的表单(编辑和更新)。 – gabrielhilal 2013-02-11 12:47:27

1

看看http://guides.rubyonrails.org/routing.html#nested-resources。 您应该可以使用嵌套的路由帮助程序(例如project_ticket_path(@project, @ticket))从您的控制器重定向到嵌套的资源。

+0

是的,但我不想在发生错误时重定向,只需重新渲染视图即可。 – user1121487 2013-02-11 12:44:52

+0

该视图的重新渲染与重新导向该显示操作相同 – tmaximini 2013-02-11 13:50:20

+0

并非如此。我正在验证邮件;重定向会导致一个新的302请求,渲染不会。 – user1121487 2013-02-11 13:52:45