开发者

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.


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 %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜