使用面向资源的控制器时在 Rails 中呈现不同的控制器操作
假设我正在制作一个像 StackOverflow 这样的问答网站。我有两个资源:问题和答案。我使用默认的 Rails RESTful 资源路由,因此每个资源都有自己的控制器和创建它的方法。
在 /questions/show
视图中,我希望允许用户提交特定问题的答案。该表单将 POST 到 /answers
,该表单将通过调用 create
方法作为请求路由到 AnswersController
。
如果答案已创建,我可以简单地重定向回原来的问题。但是,我在处理答案对象的验证失败时遇到了麻烦。我需要渲染 /question/show
视图并显示答案对象的验证错误。我不清楚如何最好地做到这一点。
以下是两个控制器的示例片段。
class AnswersController < ApplicationController
def create
@answer = Answer.new(params[:answer])
if @answer.save
redirect_to @answer.question
else
# What should go here??
end
end
end
class QuestionsController < ApplicationController
def show
@question = Question.find(params[:id])
@answer = Answer.new(:question_id => @question.id)
end
end
AnswersController
的 create 方法的 else 子句中应该包含什么内容?重定向似乎是错误的,因为该错误实际上是由同一请求引起的。调用类似 render :template =>; 'questions/show' 似乎也是错误的,因为我必须初始化模板依赖的任何实例变量。
这种调用 GET 来查看创建对象的表单和调用 POST 来实际创建对象的单独操作的风格似乎在单个控制器中运行良好。
如何跨控制器完成?
Say I'm making a Q&A site like StackOverflow. I have two resources: Question and Answer. I'm using default Rails RESTful resource routes, so each resource has its own controller and methods for creating it.
In the /questions/show
view, I want to allow the user to submit an answer for the particular question. The form will POST to /answers
, which will get routed as a request to the AnswersController
with a call to the create
method.
If the answer was created, I can simply redirect back to the original question. However, I'm running into trouble dealing with validation failures on the answer object. I need to render the /question/show
view and show the validation errors for the answer object. It's not clear to me how to best do this.
Here are example snippets of what the two controllers might look like.
class AnswersController < ApplicationController
def create
@answer = Answer.new(params[:answer])
if @answer.save
redirect_to @answer.question
else
# What should go here??
end
end
end
class QuestionsController < ApplicationController
def show
@question = Question.find(params[:id])
@answer = Answer.new(:question_id => @question.id)
end
end
What should go in the else clause of the AnswersController
's create method? A redirect seems wrong, since the error is really caused by the same request. Calling something like render :template => 'questions/show'
seems wrong too, since I have to initialize any instance variables that the template depends on.
This style of having separate actions for calling GET to view the form for creating an object and calling POST to actually create the object seems to work well within a single controller.
How can it be done across controllers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试穿一下尺寸。它重定向,但传回充满错误的狡猾答案对象。
需要添加一些细节(例如,完成后从会话中清除它)等
Try this on for size. It redirects, but passes back the dodgy answer object full of errors.
Some details need adding (eg clearing it from the session when done) etc