I have a dashboard for users where on the left side there is a sidebar with links such as Projects, Blogs, etc. I would like the user to be able to click on a link, let's say the "Projects" link, and then have the view for projects load up in the main area without refreshing the entire page. I have been trying to achieve this using AJAX, but unfortunately, things are not working as expected.
This is my understanding of how it should work. When the user clicks on the sidebar link in show.html.erb
<%= link_to 'Projects', '/dash', remote: true %>
where /dash
is set in the config/routes.rb
file to route to user's show action like this:
match '/dash' => 'users#show'
Then, the show action is triggered in users_controller.rb
:
def show
@user = User.find(params[:id])
@projects = @user.projects
respond_to do |format|
format.html # renders show.html.erb
format.js # renders show.js.erb
end
end
The show.js.erb
file is executed. It includes this line:
$('#ajax').html("<%= escape_javascript(render(:partial => 'projects/index')).html_safe %>");
This line is intended to update the #ajax div in the show.html.erb
:
<div id="ajax">
<%= render :template => 'projects/index' %>
</div>
The app/views/projects/index.html.rb
file loops through @projects and displays a list as follows:
<% @projects.each do |project| %>
<p><%= project.name %></p>
<% end %>
However, despite following this process, it seems like I have missed something as it is not working. Can anyone point out where I might be going wrong? Is there a piece of code that needs to be adjusted elsewhere? I am using Rails 3.2.13, so the lines //=jquery
and //=jquery_ujs
in
app/assets/javascripts/application.js
should have imported the required jQuery and AJAX functionality.