2012-12-09 2 views
0

두 개의 객체로 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." 
     }); 
    } 
    }); 
} 

답변

1

, 당신은 객체처럼 반환 또는있을 수 있습니다 {comment: {}, comments_count: 100 };

어쨌든 여기서 retu rned 목적은 ...

은 그래서 당신은 JSON으로 분석하고 콜백 요소에 배치해야합니다 :

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

다른 이상한 일들, 당신은 하나의 주석으로 의견 배열을 해석하는 이유와 같은과 재산을 얻으려고 노력 이드 ...하지만 질문과는 관련이 없습니다.

+0

comments_count가 업데이트되었지만 ActiveRecord :: RecordNotFound (id = undefined 인 댓글을 찾을 수 없음) 오류가 발생했으며 답변 끝에 – nilid

+1

이 새 메모에 추가되지 않았습니다. 당신은 그 객체에 부정확하게 접근하고 객체의 구조를 모른다.'comment.comment.id' 또는'comment.comment [0] .id'가 필요할 수도있다. –

+1

'console.log (JSON.stringify (comment)); ''$ ('# comments_count') .text (comment.comments_count);'콘솔을 확인한 후 도와 주셔서 감사합니다. –

관련 문제