First you need to set up a database to handle this, I personally would go with has_many: through the association, because it provides more flexibility over has_and_belongs_to_many. The choice, however, is up to you. I recommend that you look for different types of APIs and decide for yourself. This example will deal with has_many: through.
Models
# user.rb (model) has_many :favorites has_many :posts, :through => :favorites
controller
# favorites_controller.rb def create current_user.favorites.create(:post_id => params[:post_id]) render :layout => false end
Routes
match "favorites/:post_id" => "favorites#create", :as => :favorite
JQuery
$(".favorite").click(function() { var post_id = $(this).attr('id'); $.ajax({ type: "POST", url: 'favorites/' + post_id, success: function() {
Notes
This suggests a couple of things: using Rails 3, using jQuery, every favorite icon has an html identifier with a message id. Keep in mind that I have not tested the code and I wrote it in this window, so you probably have to fix some minor issues, but this should give you an idea of how I usually do it. Visual material and the like I will leave you.
If anyone finds any errors, feel free to edit this post.
amunds
source share