2011-04-01 2 views
7

부모 모델과 하위 모델 (상위 has_many : 하위)이있는 레일 3 앱을 시작하고 있습니다.다른 컨트롤러의 메서드에 유효성 검사 오류 메시지를 전달하려면 어떻게해야합니까?

새로운 부모를 만든 후에 사용자가 해당 부모 (/ parent/id)의 show 작업으로 이동하도록 설정하려고합니다. 이 견해에서 나는 어떤 아이들을 보여주기위한 부분적인 부분과 새로운 아이를 만드는 양식을 포함 시켰습니다. 새 하위를 만든 후 사용자는 새 하위가 표시 될 상위에 대한 표시 작업으로 리디렉션됩니다. 이것은 모두 의도 한대로 작동합니다.

그러나 새 자식 폼의 필드의 유효성을 검사하려고하면 발생하는 모든 오류 메시지가 양식에 나타나지 않습니다. 뷰의 필요한 줄이 있으며 올바르게 생성 된 스캐 폴드 코드에서 잘라내어 붙여 넣습니다. 자식에 대한 이러한 오류 메시지를 부모 표시 작업에 성공적으로 전달하는 방법이 있습니까?

다음은 관련 코드 스 니펫입니다. 부모님 컨트롤러에서

:

def show 
    @parent = Parent.find(params[:id]) 
    @child = @parent.children.new 

    respond_to do |format| 
    format.html # show.html.erb 
    format.xml { render :xml => @admission } 
    end 
end 

내 아이 컨트롤러에서 : 아이가 무효 인 경우 당신은 단지 부모의 쇼 페이지를 렌더링하면 어떻게

def create 
    @child = Child.new(params[:parent]) 

    respond_to do |format| 
    if @child.save 
     format.html { redirect_to(parent_path(params[:child][:parent_id]), :notice => 'Child was successfully created.') } 
       #This works as intended 
     format.xml { render :xml => @child, :status => :created, :location => @child } 
    else 
     format.html { redirect_to parent_path(params[:child][:patient_id]) } 
       #This redirects where I want it to go when validation fails but error messages are lost 
     format.xml { render :xml => @child.errors, :status => :unprocessable_entity } 
    end 
    end 
end 

답변

11

좋아,이 문제를 직접 해결했습니다. Terw의 대답에 감사드립니다. 리디렉션이 없기 때문에 잘못된 URL을 제공하는 것과 별개로 작동합니다.

단순히 세션 해시를 통해 오류를 전달한 다음 상위 컨트롤러의 하위 모델에 오류를 추가하기 만하면됩니다.

다른 예제를 찾을 수 없어서 코드를 게시하고 있습니다. 아마도 더 간단한 방법이 있지만 이것은 지금까지 완벽하게 작동합니다. 누군가 내가 미쳤다고 생각하면 설명해주십시오.

def show 
    @parent = Parent.find(params[:id]) 
    @child = @parent.children.new 
    if session[:child_errors] 
    session[:child_errors].each {|error, error_message| @child.errors.add error, error_message} 
    session.delete :child_errors 
    end 
    respond_to do |format| 
    format.html # show.html.erb 
    format.xml { render :xml => @parent } 
    end 
end 
1

?

def create 
    @child = Child.new(params[:parent]) 

    respond_to do |format| 
    if @child.save 
     format.html { redirect_to(parent_path(params[:child][:parent_id]), :notice => 'Child was successfully created.') } 
       #This works as intended 
     format.xml { render :xml => @child, :status => :created, :location => @child } 
    else 
     format.html { render :controller => :parent, :action => :show } 
       # Display the parent's show page to display the errors 
     format.xml { render :xml => @child.errors, :status => :unprocessable_entity } 
    end 
    end 
end 

크레이트 조치에 대해 이와 같은 작업을 수행하여 부모가 있는지 확인할 수도 있습니다.

@parent = Parent.find(params[:parent][:parent_id]) 
@child = @parent.children.build(params[:parent]) 

사용자가 잘못된 하위를 만들 수없고 부모에게 표시 페이지를 다시 렌더링하도록 할 수 있습니다. 사용자는 parent_id를 selfes로 설정할 수 없습니다.

+0

덕분에 내 아이 컨트롤러

def create @parent = Parent.find(params[:child][:parent_id]) @child = @parent.child.build(params[:child]) respond_to do |format| if @child.save format.html { redirect_to(parent_path(params[:admission][:parent_id]), :notice => 'Child was successfully created.') } format.xml { render :xml => @child, :status => :created, :location => @child } else if @child.errors.any? session[:child_errors] = @child.errors end format.html { redirect_to(parent_path(params[:child][:parent_id])) } format.xml { render :xml => @child.errors, :status => :unprocessable_entity } end end end 

에서 그리고 내 부모 컨트롤러

, 즉 오류 메시지가 시작되는 표시 있어요. (주위를 읽고 - 렌더링 '부모/쇼'올바른 방법입니다). 문제는 리디렉션이 없기 때문에 표시된 URL이 유효하지 않다는 것입니다. 이것은 훨씬 작은 문제이지만 여전히 이상적이지 못합니다. 부모를 먼저로드하는 방법에 대한 팁을 보내 주셔서 감사합니다 (악의적 인 사용자는 여전히 유효하지만 올바르지 않은 parent_id를 보내어 자녀를 첨부 할 수 있음). 또한 Parent.find (params [: child] [: parent_id]) 및 .build (params [: child]) 여야합니다. 현명한 사람이 되려하지 않으려 고합니다. 단지 이것을 읽는 다른 사람들을 돕기 위해 노력하고 있습니다. – brad

관련 문제