1

そのため、ページの下部にコメント用のフォーム (典型的な記事とコメントの例) があります。検証が失敗した場合は、検証エラーを表示します。

それは私のコメントコントローラコードです:

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を使用しています。また、私はまともな露出スリムを使用しています

検証が失敗した後、ページを下にスクロールしてフォームに移動したい(そのため、ユーザーは手動でスクロールする必要はありません)。それを達成する簡単な方法はありますか?

私の知る限り、アンカーを渡してレンダリングすることはできません(これで問題が解決します)。何か案は?

4

1 に答える 1

0

だから私はコメントフォームに配置されたこのjavascriptでそれを解決しました:

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

ID 'comment_errors' (My validation errors div) を持つ要素が存在する場合、そこにジャンプします。

于 2016-03-26T17:35:47.883 に答える