Rails 上的前端挑战 Ruby

Front-end Challenge Ruby on Rails

在博客应用程序中,我希望 Next Comment 按钮在用户单击后显示下一条(实例)评论。

我定义了方法并在 Comment 模型中工作,所以我的问题是面向前端的。

welcome#index:

- @articles.each do |article|
      .article
            %comment= article.comments.last.text
            = link_to "Next Comment", welcome_next_comment_path

welcome_controller:

class WelcomeController < ApplicationController

 def index
    ...
 end

 def next_comment
    find_comment
    article.comments.next(@comment)
 end

private 

 def find_comment
    ...
 end
end

我还没有测试过它,但它应该可以工作(输入或输入一些错别字)。至少它会指导你如何完成你想要的

您的 Next Comment link 具有当前评论 ID,当您在 jQuery/ajax 中单击它时,该 ID 会被传递。 ajax 方法阻止访问 link 的默认行为,并获取您正在查找的 html 页面的精确部分(页面上的评论)并将其附加到容器您点击的 link 个。

# app/controllers/welcome_controller.rb
  def next_comment
    find_comment
    @next_comment = article.comments.next(@comment)
  end


# app/views/welcome/next_comment.haml
#comment
  .article{id: "comment#{@next_comment.id}"}
    %comment= @next_comment.text
    = link_to "Next Comment", welcome_next_comment_path, data: {id: @next_comment.id, hook: 'comment-link'}


# your_view.haml
- @articles.each do |article|
  - comment = article.comments.last
  .article{id: "comment#{comment.id}"}
    %comment= comment.text
    = link_to "Next Comment", welcome_next_comment_path, data: {id: comment.id, hook: 'comment-link'}


# app/assets/javascripts/application.js
$("[data-hook='comment-link']").click(function(event)) {
  event.preventDefault();
  var url = $(this).attr('href');
  var id = $(this).data('id');
  var container = $('#comment' + id);
  $.ajax({
    type: 'GET',
    url: url,
    success: function(html) {
      container.append( $('#comment', html) )
    }
  });
});