I would like to use jQuery to refresh a partial on a page, but I can't get the partial to work because the collection it requires isn't available after the jQuery code executes.
I have a show action in the Users controller:
def show
@user = User.find(params[:id])
@title = "#{@user.first_name} #{@user.last_name}"
@posts = @user.posts.paginate(:page => params[:page], :per_page => 20 )
@discussions = @user.discussions.paginate(:page => params[:page], :per_page => 2)
end
This makes the collections @posts and @discussions available on the user show page to pass to partials as follows, in show.html.erb:
<div id="synopsis">
<%= render :partial => 'users/post', :collection => @posts %>
</div>
<div class="pagination_links">
<%= will_paginate(@posts) %>
</div>
However, let's say I want to replace the posts showing on the user show page to the user's discussions, ie using @discussions available in the show action. To do so, I set up a custom action in the Users controller called show_discussions and made the routes to it work. this is the action:
def show_discussions
respond_to do |format|
format.js
end
end
This references show_discussion.js.erb
$("#synopsis").html("<%= (escape_javascript("#{render(:partial => 'discussion_activity', :collection => @discussions)}")).html_safe %>");
This file successfully replaces #synopsis, but fills it with nothing - as the collection @discussions doesn't persist through the remote call to this action. How can I fix this such that the users discussions are made available after the remote call?
UPDATE: I make the ajax request using a js file. I specify to get the user action show_discussions when a button is clicked:
$(function() {
$('#show_discussions').live("click", function() {
$.get('/users/show_discussions');
});
$('#show_posts').live("click", function() {
$.get('/users/show_posts');
});
});