0

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."
      });
    }
  });
}

1 Answer 1

1

As I understand, you return object like:

{comment: [], comments_count: 100 }; or it may be {comment: {}, comments_count: 100 };

anyway here only two root properties of returned object...

so you should parse it as json and place to element in callback:

submitComment = function(form) {
  $.ajax("/comments/?format=json", {
    type: "post",
    dataType: 'json', // <- HERE
    data: form.serializeArray(),
    success: function(comment) {
      $('#comments_count').text(comment.comments_count); // <- AND HERE
      $.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."
      });
    }
  });
}

here are other strange things, like why you interpret comments array as single comment and trying to get property id of it... but it is not related to question.

Sign up to request clarification or add additional context in comments.

4 Comments

comments_count updates, but then I get error ActiveRecord::RecordNotFound (Couldn't find Comment with id=undefined), and new comment did't append
see note in the end of the answer. you accessing that object incorrect andI not know structure of the object, may be you need comment.comment.id or comment.comment[0].id
add console.log(JSON.stringify(comment)); just after $('#comments_count').text(comment.comments_count); check the console and show me
thanks for your help, I understand the problem,decision at the beginning of the page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.