如何使用错误消息呈现正确的页面/ URL

时间:2014-08-09 02:40:55

标签: ruby ruby-on-rails-4 routes url-routing render

我创建了一个应用程序,将学生信息分成多种形式。

一切正常,但当我尝试在验证错误后渲染Form_One时,它不会呈现相应的URL /页。

EX.
   adults/1/students/2/form_one  

   turns into

   adults/1/students/2 

   I need to render the same url so I can proceed to form_2.

模型

class Adult < ActiveRecord::Base
  has_many :students

end

class Student < ActiveRecord::Base
  belongs_to :adult

  validates :firstName, :presence   => true,
                    length: { maximum: 50 }

  validates :lastName, :presence   => true,
                    length: { maximum: 50 }

end

CONTROLLER

def update
  @adult = Adult.find(params[:adult_id])
  @student = Student.find(params[:id])
  if @student.update_attributes(student_params)

    ###IF PASS REDIRECT TO THE NEXT FORM
    if URI(request.referer).path == form_one_adult_student_path(@adult, @student)
      redirect_to form_two_adult_student_path(@adult, @student)
    elsif URI(request.referer).path == form_two_adult_student_path(@adult, @student)
      redirect_to form_three_adult_student_path(@adult, @student)
    else
      redirect_to adult_path(@district, @adult)
    end  
  else
    error_messages = @student.errors.messages
    @adult = Adult.find(params[:adult_id])
    @student = Student.find(params[:id])
    @student.errors.messages.merge!(error_messages)

    ###IF ERROR AND ON FORM_ONE RENDER FORM_ONE
    if URI(request.referer).path == form_one_adult_student_path(@adult, @student)

      ###FOR SOME REASON THIS RENDERS adults/1/students/2
      ###BUT I NEED IT TO RENDER adults/1/students/2/form_one
      render 'form_one'
    end
  end
end

def form_one
  @title = "Student Information"
  @adult = Adult.find(params[:adult_id])
  @student = Student.find(params[:id])
end

def form_two
  @title = "Parent Information"
  @adult = Adult.find(params[:adult_id])
  @student = Student.find(params[:id])
end

路线

resources :adults do
  resources :students do
    member do
      get :form_one, :form_two
    end
  end
end

1 个答案:

答案 0 :(得分:0)

  ###FOR SOME REASON THIS RENDERS adults/1/students/2
  ###BUT I NEED IT TO RENDER adults/1/students/2/form_one
  render 'form_one'

尝试使用redirect_to代替render

请记住呈现模板与制作 HTTP请求之间的区别。尝试假装您是HTTP客户端并考虑请求和响应。有时查看服务器日志有助于查看哪些控制器操作发生,按顺序排列。查找Processing students#updateRedirecting to ...等行。

将来,您可能希望尝试resourceful routes而不是#show