I need to render json with two objects How to do it well?
The initial version was:
/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."
});
}
});
}
I want to add a dynamic update number of comments,, and I think to do this as:
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
But I do not understand how to add comments_count to the script javascripts/comment.js. All my attempts to insert comments_count, like:
$('#comments_count').html(comments_count);
I get an error or the answer "true"
please help me! and thanks in advance!
==== update =====
eicto, thank you, current function is:
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."
});
}
});
}