2つのオブジェクトで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
javascripts / 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
しかし、comments_countをスクリプトjavascripts/comment.jsに追加する方法がわかりません。以下のように、comments_countを挿入しようとするすべての試み:
$('#comments_count').html(comments_count);
エラーまたは「true」という答えが表示されます
私を助けてください!よろしくお願いします!
====更新=====
eicto、ありがとう、現在の機能は次のとおりです。
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."
});
}
});
}