As you have discovered her are many ways to accomplish a like button. What I showed was a perpetual like, every time you clicked like, it would update the count by 1. Probably not a realistic example, but I didn't want to get into the logic of seeing to it that a user can only 'like' once. I really was just illustrating the fastest (I think) way to get it working, and demonstrate some Rails features.
By putting the JavaScript in images/like.js.erb, all you have to do to run it is do the
format.js
from within the like action.
That's pretty minimalist.
A more minimalist method would have been:
<%= link_to "Like", "/images/like", :remote=> :true %>
<div id="likecount">
<%= "#{@image.like} #{pluralize(@image.like,'like')} %>
</div>
Then the JavaScript would be:
$('#likecount').html('<%=j "#{@image.like} #{pluralize(@image.like,'like')}" %>')
(Yes, forgot quotations in earlier post, you may have to play around, because I don't have 3.1 running anywhere I can't test anything, so NOTHING is tested!)
If you put the code in assets/javascript/images.js, then you have to do more work to wire that code into your app. You'd have to put in in a function, and bind a click to that function. That may be the correct way to go though, it depends on how complicated your JavaScript gets, what else you do in JavaScript on the page, etc. At some point it may be cleaner to have all your JavaScript in one file, but for the sake of a simple example, I put it in like.js.erb, mostly to illustrate the format.js feature.
Last edited by BradHodges (2011-10-30 11:06:21)
Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.