[英]Front-end Challenge Ruby on Rails
在博客應用中,我希望“ Next Comment
按鈕在用戶單擊后顯示下一個(實例)評論。
我已經定義了該方法並且可以在Comment
模型中工作,所以我的問題是面向前端的。
如何動態顯示最近的評論? 意思是,rails知道它是哪個注釋,因此它能夠在線顯示下一個注釋。
如何使其顯示在%comment
html元素中? (AJAX?)
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
鏈接具有當前的評論ID,當您在jQuery / ajax中單擊它時,該ID就會傳遞。 ajax方法可防止訪問鏈接的默認行為,並獲取要查找的html頁面的精確部分(頁面上的注釋),並將其附加到您單擊的鏈接的容器中。
# 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) )
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.