0

我正在构建的博客上有一个评论表。

博客文章很长,因此表单位于页面底部的屏幕外。

如果评论未通过验证,则用户将返回页面顶部,但错误消息会显示在表单所在的位置。

发生这种情况时,我希望浏览器关注评论部分,以便用户可以看到验证错误消息

这是我的 comments_controller 的创建操作:

def create
  @article = Article.find(params[:article_id])
  @comment = @article.comments.build(params[:comment])
  if @comment.save
    redirect_to article_path(@article), notice: "Thanks for your comment"
  else
    # is there anyway to pass an id (like #comments) to this render call??
    render 'articles/show'
  end
end

如您所见,render 'articles/show'如果验证失败,我会打电话。我希望能够做这样的事情:

render 'articles/show', :anchor => '#comments'

在理想情况下,上面的代码会渲染article#show,并将视口焦点设置在评论部分。我知道我可以在使用时通过锚点link_to,但我可以这样做render吗?

这样的事情可能吗,还是我需要使用 Ajax 解决方案?

4

2 回答 2

1

您不需要 Ajax - 简单的 jquery 应该可以工作。

像这样的东西(用你的错误类替换'.error-messages'):

$(document).ready(function(){

  if ($(.error-messages).length) {
      $('body').animate({scrollTop:$('.error-messages').offset().top})
  }

})

在页面加载时,如果有任何错误消息,页面将滚动到错误消息。

于 2012-11-04T22:20:04.157 回答
1

我不认为render可以做你想做的工作。因为render将呈现整个页面(包括布局),但不是您要更改的唯一文本。

我建议你使用 jQuery 的 Ajax,它更加优雅和简单。

于 2012-11-04T22:17:22.290 回答