我正在尝试用rails编写的野兽论坛,并将此作为我一直面临的问题的一个例子.
论坛有一个主题/节目动作和视图,底部有一个表单,可以在主题中创建一个新帖子.
提交表单会发布到帖子/创建,如果验证通过重定向回主题/显示并且工作正常,但是如果验证失败(遗漏了正文字段),您将被重定向到相同的主题/显示并返回到表单,没有验证错误...通常如果验证失败,你就会留下什么/使用render创建:action => new.
验证是否在重定向中丢失,以及使其运行的最佳方法是什么?
见下面的代码:
PostsController.rb
def create
@post = current_user.reply @topic, params[:post][:body]
respond_to do |format|
if @post.new_record?
format.html { redirect_to forum_topic_path(@forum, @topic) }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
else
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(forum_topic_post_path(@forum, @topic, @post, :anchor => dom_id(@post))) }
format.xml { render :xml => @post, :status => :created, :location => forum_topic_post_url(@forum, @topic, @post) }
end
end
end
Run Code Online (Sandbox Code Playgroud)
TopicsController.rb
def show
respond_to do |format|
format.html do …
Run Code Online (Sandbox Code Playgroud) 我有一个令人讨厌的大型登陆页面,中间有一个注册表格.如果我提交表单并且验证失败,我想再次渲染着陆页,但我希望将其向下滚动到注册表单,以便他们可以看到错误并进行编辑.是否可以使用该render
方法跳转到表单,或者我需要做 redirect_to "account/new#theFormID"
什么?
我宁愿不做重定向,因为你必须在会话中保存表单信息,重新填充表单,等等,我想坚持常规
if @resource.save then redirect_to ...
else render "new"
end
Run Code Online (Sandbox Code Playgroud)