두 개의 객체로 json을 렌더링해야합니다. 잘 수행하는 방법은 무엇입니까?두 개의 객체로 json을 렌더링하십시오.
초기 버전이었다 :
/controller/comments_controller.rb
def create
....
respond_to do |format|
format.html { redirect_to @comment.commentable, flash[:notice] => t('comment.actions.added') }
format.json { render :json => @comment }
end
end
자바 스크립트/comment.js :
submitComment = function(form) {
$.ajax("/comments/?format=json", {
type: "post",
data: form.serializeArray(),
success: function(comment) {
$.get("/comments/" + comment.id, function(commentHtml) {
newComment = $(commentHtml).hide();
commentsList = $('#' + comment.commentable_type + comment.commentable_id + 'Comments');
commentsList.append(newComment);
newComment.show('slow');
});
$(form.selector + " textarea").val("");
},
error: function() {
showMessage({
title: "Error",
message: "Error occured. Please try resubmit the data."
});
}
});
}
나는 동적 업데이트를 추가 할 코멘트의 숫자, 그리고이 일을 생각 :
def create
....
respond_to do |format|
format.html { redirect_to @comment.commentable, flash[:notice] => t('comment.actions.added') }
format.json { render :json => {comment: @comment, comments_count: @comment.commentable.comments.count }
end
end
그러나 javascripts/comment.js 스크립트에 comments_count를 추가하는 방법을 모르겠다.
저를 도와주세요
$('#comments_count').html(comments_count);
내가 "true"로 오류 또는 답변을 얻을 : 내 모든 시도는 같은 comments_count를 삽입! 그리고 미리 감사드립니다!
==== 업데이트 =====
eicto, 감사, 현재의 기능은 다음과 같습니다
{comment: [], comments_count: 100 };
: 내가 알고있는 것처럼
submitComment = function(form) {
$.ajax("/comments/?format=json", {
type: "post",
dataType: 'json',
data: form.serializeArray(),
success: function(comment) {
$("h2#comments_count").text(comment.comments_count);
$.get("/comments/" + comment.comment.id, function(commentHtml) {
newComment = $(commentHtml).hide();
commentsList = $('#' + comment.comment.commentable_type + comment.comment.commentable_id + 'Comments');
commentsList.append(newComment);
newComment.show('slow');
});
$(form.selector + " textarea").val("");
},
error: function() {
showMessage({
title: "Error",
message: "Error occured. Please try resubmit the data."
});
}
});
}
comments_count가 업데이트되었지만 ActiveRecord :: RecordNotFound (id = undefined 인 댓글을 찾을 수 없음) 오류가 발생했으며 답변 끝에 – nilid
이 새 메모에 추가되지 않았습니다. 당신은 그 객체에 부정확하게 접근하고 객체의 구조를 모른다.'comment.comment.id' 또는'comment.comment [0] .id'가 필요할 수도있다. –
'console.log (JSON.stringify (comment)); ''$ ('# comments_count') .text (comment.comments_count);'콘솔을 확인한 후 도와 주셔서 감사합니다. –