Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
How do I render partial via ajax in rails3 and jQuery

I could do sth like this in rails 2:

def show_rec_horses
  rec_horses = Horses.find(:all)
  page["allHorses"].replace_html :partial => "horses/recommended", :locals => 
 {:rec_horses => rec_horses}
end

How do I do this in Rails3 with jQuery. So how can I replace html of my div with a partial via ajax call(link_to :remote => true) in Rails3.

I tried sth like (in my show_rec_horses.js.erb):

$("#interactionContainer").update("<%= escape_javascript(render("horses/recommended"))%>");

And nothing happens. I tried some other variations but none worked. What am doing wrong? Should this be approached in some other way? Any answer would be greatly appreciated.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Okay, let's start with the controller.

def show_rec_horses
  @rec_horses = Horses.find(:all)

  respond_to do |format|
    format.html # show_rec_horses.html.erb
    format.js   # show_rec_horses.js.erb
  end
end

This will make sure the correct templates are being rendered for either a html request or a javascript request. If you just need to respond to a javascript request, delete the html part.

Now let's say you have a page containing the following:

<p><%= link_to 'Show Horses', show_rec_horses_path, remote: true %></p>

<div id="interactionContainer"></div>

Clicking the link will make a request to the show_rec_horses action in your controller, this action will render the javascript file show_rec_horses.js.erb.

This javascript file should contain something like this:

$('#interactionContainer').html('<%=j render partial: 'horses/reccommended', locals: { rec_horses: @rec_horses } %>')

Now your container will be filled with the content of horses/_reccommended.html.erb, which for example could contain:

<% rec_horses.all.each do |rec_horse| %>
  <p><%= rec_horse.name %></p>
<% end %>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!