【发布时间】:2011-02-20 16:24:32
【问题描述】:
他们是两个用户:
用户 - 登录用户
访客 - 未登录的访客。
用户和访客可以发布问题。要发布问题,客人必须指定他的电子邮件。
它们是两个视图“new.html.erb”和“new_for_guest.html.erb”。第一个依赖于@user 变量。第二个没有。
当由来宾创建的问题验证失败时,应呈现“new_for_guest.html.erb”,保留所有输入的数据。
代码如下:
def new
@question = Question.new
guest = session[user_id].nil?
respond_to do |format|
if guest
format.html { render "new_for_guest" }
else
format.html { render "new" }
end
end
end
def create
@question = Question.new(params[:question])
guest = session[user_id].nil?
respond_to do |format|
if @question.save
flash[:notice] = 'Question was successfully created.'
format.html { redirect_to(@question) }
else
if guest
format.html { render :action => "new_for_guest" } # problem
else
format.html { render :action => "new" }
end
end
end
当访客验证失败并呈现“new_for_guest”视图时,我在浏览器中看到 url“/questions”,而不是“/questions/new”。因此,所有用于“新建”操作的样式表都消失了。
当用户验证失败并呈现“新”视图时,我看到正确的 url“/questions/new”并且一切正常。
当我只是说
format.html{ redirect_to new_question }
“新”动作将被渲染,但用户输入的所有数据都消失了。
我需要在“questions/new”上下文中呈现“new_for_guest”视图。
怎么做?
更新
我注意到脚手架生成的未修改代码的相同行为。
当通过创建验证失败时,会再次呈现新的操作,但在 URL 中显示的是“/questions”而不是“/questions/new”。
这很奇怪。这是正确的行为吗?
我发现了类似的未回答问题Rails create action is redirecting to index when it should be rendering the new action
【问题讨论】:
-
为什么要根据
action定义样式表?你不能让他们依赖view吗? -
因为我从布局中决定要包含哪个资产包(css 和 js),具体取决于控制器和操作,正在执行。
标签: ruby-on-rails model-view-controller view