Rails 4: 滚动浏览器 window 提交失败后形成表单(验证错误)

Rails 4: scroll browser window to form after failed submission (validation errors)

所以我在页面底部有评论表格(典型文章和评论示例)。如果验证失败,我会显示验证错误。

那是我的评论控制器代码:

class CommentsController < ApplicationController
  before_action :authenticate_admin!, only: [:destroy]
  expose(:article)
  expose(:comment, attributes: :comment_params)
  expose(:reply) { Reply.new }

  def create
    comment.article = article
    if verify_recaptcha(model: comment, message: t('captcha_verification_error')) && comment.save
      flash[:comment_notice] = t('comment_created_successfully')
      redirect_to article_path(article) + '#comments'
    else
      flash[:comment_errors] = comment.errors.full_messages
      render 'articles/show'
    end
  end

  def destroy
    comment.destroy
    redirect_to article_path(article)
  end

  private

  def comment_params
    params.require(:comment).permit(:author, :content)
  end
end

这是表格:

= simple_form_for(comment, url: article_comments_path(article)) do |f|
  - if flash[:comment_errors]
    .alert.alert-danger
      strong= pluralize(flash[:comment_errors].count, 'error') + ' prohibited this article from being saved:'
      - flash[:comment_errors].each do |msg|
          ul
            li= msg
  fieldset class='form-group'
    = f.label t('author')
    = f.text_field :author, class: 'form-control', placeholder: t('who_are_you')
  fieldset class='form-group'
    = f.label t('content')
    = f.text_area :content, class: 'form-control', rows: 6, placeholder: t('what_do_you_want_to_say')
  fieldset class='form-group'
    = recaptcha_tags
  fieldset class='form-group'
    = f.submit t('create_comment'), class: 'btn btn-primary'

对于我使用的表格 simple-form. Also I'm using decent exposure and slim

我希望我的页面在验证失败后向下滚动到表单(这样用户就不必手动滚动)。有没有简单的方法可以实现?

AFAIK 我无法通过锚点进行渲染(这会解决问题)。有什么想法吗?

所以我用这个 javascript 放在评论表中解决了这个问题:

javascript:
  if (document.getElementById("comment_errors")) {
    location.hash = '#new_comment';
  }

当 ID 为 'comment_errors' 的元素(我的验证错误 div)存在时,它会跳转到它。