Question

How does jQuery .get() work with Rails methods? I've set up a method in a documents controller called templates and I'd like to access that method from a JS method in a separate JS file. From doing some research I found that using .get() is the best way to access Rails methods, but when I do, for instance, var templates = $.get("/documents#templates", function (data) { console.log(data) }, it's just console logging the entire /documents HTML DOM structure.

I'm guessing I need to "hijack" the route if you will, but I tried adding a custom route and the console log is still returning the HTML page, not even reaching my Rails controller.

If it helps (although I doubt it, since removing this entirely doesn't alter the console log results), here's my templates method in the controller:

def templates
  @templates = DocumentTemplate.all
  @output = []
  @templates.each do |template|
    @output = template.content
  end
  respond_with(@output)
end
Was it helpful?

Solution

If you'd like to respond to jQuery's GET request with snippets of HTML you could consider rendering a partial layout (which won't include the full application layout). In your controller the response may look like:

def templates
  @templates = DocumentTemplate.all

  if request.xhr?
    render :partial => 'templates', locals: {:templates => @templates}
  else
    # respond with your normal layout if required
  end
end

Then in your app/views/documents/ folder create a partial file called _templates.html.haml (or .erb). Note the leading underscore in partial names.

You'll have access to a templates local variable to loop over in your partial file (syntax here is for HAML):

- templates.each do |template|
   # do what's required to present each template instance here

Then your jQuery GET request should receive just the partial snippets of HTML:

$.get("/documents/templates", function(data) {
  console.log('data');
  alert("Load was performed.");
});

OTHER TIPS

What exactly do you want to return? There are a few different approaches, depending on your needs.

$(data).find('selector') is the least elegant way. You can extract what you need from the full response with jQuery.

respond_with(@output, :layout => !request.xhr? ) will render the page without the surrounding application.html file. The following is a way to render a different partial for jQuery.

respond_with(@output) do |format|
  format.html { render partial: 'templates' if request.xhr? }
end

You could also send back JSON easily enough if that's what you require. There's a nice blog post here about various approaches to Rails AJAX: http://madebydna.com/all/code/2011/12/05/ajax-in-rails-3.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top