I have queried on user posts (nested resources, obviously) and have a long list of posts from different users. I would like the user to be able to click a little star next to each post to favorite that particular post through ajax. Any suggestions on how to achieve this? The trouble I’m running into is multiple favorite buttons on one page, favoriting multiple posts.
This is sorta like Gmail does with favorite emails in their inbox. Actually, it’s exactly like that.
First you need to set up the database to handle this, personally I’d go with a has_many :through association because it provides more flexibility over has_and_belongs_to_many. The choice, however, is up to you. I recommend you look up the different types in the API and decide for yourself. This example will deal with has_many :through.
Models
Controller
Routes
jQuery
Notes
This assumes a couple of things: Using Rails 3, using jQuery, each favorite icon has an html id with the post id. Keep in mind I’ve not tested the code and I wrote it in this window so you probably have to fix some minor problems, but it should give you an impression of how I usually does this. The visual stuff and such I’ll leave up to you.
If anyone spot any mistakes please feel free to edit this post.