Chris Williams
Chris Williams

Reputation: 432

Rails render partial with JSON object

In my rails app I have a javascript callback after the a post is created that polls a processing endpoint to check if an image has finished processing and then updates the view like this:

create.js.erb create callback

// start polling for processed image
function imageProcessed() {
  $.ajax({ url: "/posts/" + <%= @post.id %> + "/processing"})
    .done(function(data) {
      if (data.processing) {
        setTimeout(imageProcessed(), 2000);
      } else {
        // append image url when processed
        $("#js-capture-container").html('<img src="' + data.image_url + '" alt="image">');
      }
    });
}

imageProcessed();

posts_controller.rb endpoint

def processing
  data = { processing: @post.image_processing }
  if [email protected]_processing?
    data[:image_url] = @post.image_url(:pair)
  end
  render json: data
end

This works fine, but I would like to take the data returned in the ajax and render the already existing _post.html.erb partial with this data.

Something like return an updated instance of @post and then render that object into the partial.

"<%= escape_javascript(render @post) %>" in create.js.erb

Any ideas would greatly help, thanks!

Upvotes: 2

Views: 2484

Answers (1)

Chris Williams
Chris Williams

Reputation: 432

I was able to get it work by rendering the partial as a string of HTML inside of the json object, similar to what's being done in this question: rails 3 - How to render a PARTIAL as a Json response

I changed the if statement in post_controller.rb to:

if [email protected]_processing?
  data[:partial] = render_to_string(@post)
end

and then in create.js.erb changed the callback to:

$("#js-capture-container").html(data.partial);

very nice, very clean.

Upvotes: 1

Related Questions