2013-02-11 49 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