Reputation: 4403
rails newbie herem, I'm looking to learn a little bit about jquery so I figured I'd try to switch between my partial views using AJAX.
Right now on my user's dash I have a link to their 'likes' page, it requires a full reload to see the 'likes' page, how would I change this to refresh with the likes_user_path@user)??
views/pages/home.html.erb
<div id="left">
<div id="dash-statistics">
<a href="<%= likes_user_path(@user) %>">
<div id="likes" class="stat">Likes
<%= @user.likes.count %>
</div>
</a>
</div>
</div>
<div id="right">
<div id="content">
</div>
</div>
UsersController
def likes
@title = "Likes"
@user = User.find(params[:id])
@like_stuff = @user.likes.paginate(:page => params[:page])
render 'show_likes'
end
Upvotes: 2
Views: 1823
Reputation: 6516
What I understand is that you want to reload the likes
by clicking a link, by using ajax, in your user dashboard.
First thing to do is rewrite the link, and add a :remote => true
like this:
<%= link_to "Likes", likes_user_path(@user), :remote => true %>
Then, in your controller, make sure you have a respond_to :html, :js
at the top (there can of course be other options, but :js
has to be among them)
After that, you could do a function called likes
in your controller which to use for loading the likes, which looks something like yours, only you don't do render
at the end, but respond_with @likes
. By having :js
in the respond_to
filter, Rails will automagically act accordingly when supposed to.
Next, make a corresponding view called likes.js.erb
(i'm not exactly sure if coffeescript will work out of the box in this case) in which you put something like
$('#likes').html('<%= escape_javascript(render "likes", :likes => @likes) %>');
This assumes that in your main view in which you want to render the likes ,there's an element with the id=likes
which could look like this:
<div id="likes">
<%= render "likes", :likes => @likes %>
</div>
and there's also a _likes.html.erb
partial which renders the likes
<% likes.each do |like| %>
<div>
<%= like.name %>
</div>
<% end %>
And with this I think I pretty much covered it.
Upvotes: 8