2011-08-18 6 views
2

특정 계정과 연결된 사람을 만든 후 어떻게 계정 페이지로 다시 리디렉션합니까? 여기 다른 컨트롤러에서 SHOW 동작으로 리디렉션

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

코드입니다 : 다음과 같이

ACCOUNT_ID은 URL 매개 변수를 통해 사람을 만들 행동에 전달

<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"} 

왜 DESTROY 동작으로 redirect_to 라우팅이 사용됩니까? SHOW 액션을 통해 리디렉션하고 싶습니다. 어떤 도움이라도 대단히 감사하겠습니다.

+0

'rake routes' 그리고 생성 된 모든 경로를 확인하여 누락 된 부분을 확인하십시오. –

+0

문제는 누락 된 경로가 아닙니다. 그는 단지'account_path (nil)'로 라우팅하려하고있다. – numbers1311407

답변

7

params[:account_id]는 형태로 존재하지만 create에 전달할 때 params[:person][:account_id]

params[:account_id]를 통해 액세스 것, 그래서 당신은 nil, 따라서 나쁜 다른 루트의 person 해시에 따라 그것을 보내는. 솔직히 말해서 이유는 모르지만 resource_path(nil)은 대신 destroy으로 라우팅됩니다. 두 경우 모두 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 

레일은 본질적으로 레코드의 클래스 경로를 확인하는, 그리고 id

+0

왜이 투표를 취소 했습니까? –

+0

은 편견을 갖지 않지만 같은 생각이 들었습니다. – numbers1311407

+0

@ NEW 계정에 @account = Account.find_by_id (params [: account_id])를 추가했는데 이제는 위에서 설명한 redirect_to가 작동합니다. 당신의 도움을 주셔서 감사합니다. –

1

#to_param에서 나는 hidden_field를 사용을 통해이 통과되지 않을 것이 점점이 마지막 옵션을 이해할 것이다. 대신, 중첩 사용하십시오 자원 :

@account 개체를이 같은 라인 양식을 렌더링 작업에서 설정해야합니다
<%= form_for [@account, @person] do |f| %> 
    ... 
<% end %> 

:

resources :account do 
    resources :people 
end 

은 다음 양식에 대한 계정 개체가

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

그런 다음 양식을 제출하면 해당 작업에 해킹없이 params[:account_id] 해킹이 발생합니다.

지저귀다!

+0

이 작업은 가능하지만 내 모델 간의 관계가 이보다 더 복잡하기 때문에이 방법을 사용하지 않기로했습니다. 당신의 도움을 주셔서 감사합니다. –

관련 문제