2011-08-18 64 views
2

創建與特定帳戶關聯的人員後,如何重定向回帳戶頁面?重定向到另一個控制器中的SHOW操作

的ACCOUNT_ID通過URL參數傳遞給CREATE人稱動作如下:

http://localhost:3000/people/new?account_id=1 

下面是代碼:

<h2>Account: 
    <%= Account.find_by_id(params[:account_id]).organizations. 
     primary.first.name %>  
</h2> 

<%= form_for @person do |f| %> 

    <%= f.hidden_field :account_id, :value => params[:account_id] %><br /> 
    <%= f.label :first_name %><br /> 
    <%= f.text_field :first_name %><br /> 
    <%= f.label :last_name %><br /> 
    <%= f.text_field :last_name %><br /> 
    <%= f.label :email1 %><br /> 
    <%= f.text_field :email1 %><br /> 
    <%= f.label :home_phone %><br /> 
    <%= f.text_field :home_phone %><br /> 
    <%= f.submit "Add person" %> 

<% end %> 

class PeopleController < ApplicationController 

    def new 
     @person = Person.new 
    end 

    def create 
     @person = Person.new(params[:person]) 
     if @person.save 
      flash[:success] = "Person added successfully" 
      redirect_to account_path(params[:account_id]) 
     else 
      render 'new' 
     end 
    end 
end 

當我提交上述形式出現以下錯誤消息:

Routing Error 

No route matches {:action=>"destroy", :controller=>"accounts"} 

爲什麼redirect_to路由到DESTROY操作?我想通過SHOW操作重定向。任何幫助將不勝感激。

+0

'耙路線'並檢查所有生成的路線,看看你缺少什麼。 –

+0

問題不是缺失的路線。他只是試圖路由到'account_path(nil)'。 – numbers1311407

回答

7

params[:account_id]存在形式,但是當你把它傳遞給create你沿着person散列發送它,所以你通過params[:person][:account_id]

params[:account_id]訪問它是nil,因此不好路線。說實話,我不知道爲什麼,但resource_path(nil)結束路由到destroy而不是show。無論哪種情況,這是一條沒有id參數的斷路線。

# so you *could* change it to: 
redirect_to account_path(params[:person][:account_id]) 

# or simpler: 
redirect_to account_path(@person.account_id) 

# but what you probably *should* change it to is: 
redirect_to @person.account 

Rails會本質上理解這個最後的選擇,從類的記錄確定的路徑,並獲得id#to_param

+0

這是爲什麼被低估? –

+0

不要偏,但我想知道的一樣。 – numbers1311407

+0

我將@account = Account.find_by_id(params [:account_id])添加到了我的NEW方法中,現在我的上面有redirect_to。謝謝你的幫助。 –

1

我不會通過使用hidden_field通過這一點。相反,使用嵌套的資源:

resources :account do 
    resources :people 
end 

然後有形式的帳戶對象:

<%= form_for [@account, @person] do |f| %> 
    ... 
<% end %> 

@account對象應該呈現的形式,像這樣的線路的動作設置:

@acccount = Account.find(params[:account_id]) 

然後,當表單提交你必須在行動params[:account_id]不醜hidden_field黑客得到它。

Yippee!

+0

這有效,但我決定不採用這種方法,因爲我的模型之間的關係比這更復雜。謝謝你的幫助。 –

相關問題