在执行验证消息时,在表单(验证)错误时在不同控制器中呈现视图

时间:2013-02-13 16:12:47

标签: ruby-on-rails ruby-on-rails-3

我的第一个Rails应用程序出现以下问题

首先,我使用Scaffolding生成患者实体。 但是,我希望在我的主页中显示Patient添加表单,该表单由控制器PagesController及其操作Home控制。我刚刚在我的主页上使用Patient添加的形式渲染了局部视图。

提交表单后,如果添加成功,则可以正常工作。但是,如果验证失败,它会将我带到患者/新人(而不是我的主页),显示表单错误。这是因为PatientsController中的代码

if @patient.save
    format.html { redirect_to @patient, notice: 'Patient was successfully created.' }
    format.json { render json: @patient, status: :created, location: @patient }
  else
    format.html { render action "new" }
    format.json { render json: @patient.errors, status: :unprocessable_entity }

而不是这个我希望在出现错误的情况下,它应该让我回到显示错误的主页(提交表单的地方)。我尝试了以下操作:

format.html { render :controller => "pages", :action => "home" }

但是我收到了这个错误

Missing template patients/home, application/home with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: * "/Users/xhorxhi91/Sites/dentarails/app/views"

我也尝试过这个:

format.html { render 'pages/home' }

这只调用视图,而不调用方法Home,因此不会重新创建在该方法中创建的任何对象。此外,错误也没有进行。我知道我可以从我的方法中重新创建对象,但我知道这是不好的做法。

另外我知道我不能使用redirect_to方法,因为不会携带错误消息。

有什么建议吗?我是Ruby的新手,所以我不确定我的架构是否正确。

1 个答案:

答案 0 :(得分:0)

如果您的routes.rb显示

match 'pages/home' => "pages#home", as: "pages_home"

然后你可以写

format.html { render pages_home_path }