渲染:validation后新的没有到正确的位置
我有一个在post模型中validation的“新”表单。 当validation器启动时,它会呈现错误。
新的post页面路径位于’/ posts / new’
在validation时,新的post页面路径位于’/ posts’..我需要它回到’/ posts / new’。
这是我的控制器:
def create @post = current_user.posts.build(params[:post]) if @post.save redirect_to public_post_page_path(@post.public_url) else render :action => :new end end
我觉得这可能与我的表格有关。 所以这是formtastic的第一行:
{:id => "post_form"} do |form| %>
这是rails的正确行为。
在创建操作中,它只是呈现“新”视图文件。 因此,url将是/ posts,但视图将正确显示表单。 这种行为没有错; 一般来说,轨道惯例是好的forms。 如果你只渲染新的内置轨道错误也可以工作; 但是如果你重定向,他们将无法显示。
如果你真的想要回到那个url,你需要使用:
redirect_to
而不是渲染。
如果validation失败,用户应该看到包含错误的表单并保留在/posts/new
。 这就是你想要的,对吧?
有一种简单的方法可以实现这一目标。
在表单上设置remote: true
以防止url前进。 处理ajax:success
使用新渲染的表单替换页面上的表单ajax:success
。
$('form[data-remote=true]').on 'ajax:success', (e, data, status, xhr) -> if isHTML(data) thisForm = "form[id=#{@getAttribute('id')}]" $(thisForm).replaceWith $(data).find(thisForm)
isHtml()
函数来自这个问题 。