2015-01-14 1 views
0

유용하고 유용한 솔루션을 구축하면 here이 표시되며 업데이트 콜백도 수정하려고합니다.(이전 개체 대신) javacript 콜백에서 업데이트 된 개체에 액세스하는 방법

문제는 데이터를 추출하려고 시도하는 특정 unit은이 콜백이 성공적으로 update 동작에 의해 트리거되었지만 항상 캐시 된 이전 버전입니다.

// callback triggered by the update action 

$('.best_in_place').bind("ajax:success", function() { 
    ... 
    console.log(unit.duration); 
    // which is exactly the same as 
    console.log(<%= Unit.find(unit.id).unit_users.pluck(:duration).sum %>); 
    // and both print the OLD duration val instead of the updated val which is in the database 
}); 

과 unit_users_controller 코드

...

def update 
    @unit = @unituser.unit 

    respond_to do |format| 
     if @unituser.update(unit_user_params) 
     @unit.reload 
     logger.info('-----------------------------------------------------------------') 
     logger.info('@unit.duration in the controller is ' + @unit.duration.to_s) # which is the correct value 
     logger.info('-----------------------------------------------------------------') 
     gon.unit_duration = @unit.duration # an experiment which didn't work for me 
     format.json {respond_with_bip(@unituser) } 
     else 
     # format.html { render :action => 'edit' } 
     format.json { respond_with_bip(@unituser) } 
     end 
    end 
    end 

나는 unit.reload의 여러 버전을 시도했습니다, 아무것도 할 수 없습니다. 어쩌면 내가 잘못된 장소에 넣었을거야?

+0

컨트롤러 코드를 게시 할 수 있습니까? –

+0

@RodrigoZurek 컨트롤러 코드와 관련이 없습니다. 컨트롤러는 이것과 아무런 관련이 없습니다. 이것은'.js.erb' 파일이 어떻게 작동하는지 오해 한 것입니다. – meagar

+0

컨트롤러와 관련이 있습니다. 컨트롤러를 통과해야하는 업데이트 된 개체를 원한다면 어떻게 든 다시 가져와야합니다. –

답변

1

은 어쩌면 당신을 도울 것입니다, 내 코드입니다

$(document).ready(function() { 
    $('.price_bind').bind("ajax:success", function (event, data, status, xhr) { 
     var parsed_data = jQuery.parseJSON(data); 
     $(this).text(parsed_data.newprice); 
     $(this).parentsUntil('body').find(".totalpricep span").text(parsed_data.totalprice); 
    }); 
} 

보기 :

<%= best_in_place detail, :price, :classes => 'price_bind', :path => purchase_detail_path(@purchase, detail)%> 

컨트롤러 :

def update 
    respond_to do |format| 
     if @detail.update_attributes(params[:detail]) 
     @[email protected]_bal 
     @r=false 
     if @detail.purchase != nil 
      @[email protected] 
     if params[:detail]['status'] && @purchase.step==1 
      @remdet = @purchase.details.where(:step => 1, :status => false) 
      if @remdet.empty? 
      @purchase.update_attribute(:step, 2) 
      @r=true 
      end 
     end 
     else 
      @p=nil 
     end 
     format.html { redirect_to @detail, notice: 'Detail was successfully updated.' } 
     format.json { render :json => {:newprice => @n, :totalprice => @p, :newstatus => @detail.status, :refresh => @r}} 
     else 
     format.html { render action: "edit" } 
     format.json { render json: @detail.errors, status: :unprocessable_entity } 
     end 
    end 
    end 
+0

컨트롤러에서 format.json은 속임수가 –

+0

이지만 format.json에는 {respond_with_bip (@unituser)}가 없으므로 필드를 업데이트하려는 경우 필수적이라고 생각했습니다. ?? – dwilbank

+0

개체는 @ detail.update_attributes (params [: detail]) 또는 원하는 다른 업데이트 바로 전에 업데이트됩니다. 원하는 경우 컨트롤러에서 응답 할 수 있습니다.이 경우 JSON 응답이 필요하며 원하는 새 객체의 측면을 반환 할 수 있습니다. –

1

이것은 캐싱과 관련이 없습니다. Ruby 코드는 서버 -side로 평가되며, JavaScript가 클라이언트에 전송되기 전에 AJAX 요청이 발생할 수있는 한 한 번만 평가됩니다. 같은

console.log(<%= Unit.find(unit.id).unit_users.pluck(:duration).sum %>); 

모든 클라이언트가 볼 수는 무언가 :

console.log(32); // or whatever the sum is 

현재 <%= %>을 사용할 수 없습니다

는 클라이언트가이 줄을 볼 수 없습니다. 그것은 항상 당신에게 원래의 가치를 줄 것입니다. 대신 AJAX 요청에 대한 응답으로 클라이언트에 새 값을 보내야합니다.

자바 스크립트 : 나는 언젠가 전에 여기이 하나를했다

+0

Woops - 그 Unit.find는 심야 어리 석음이었습니다. 지금은 분명합니다. 감사! – dwilbank

관련 문제