stewart715
stewart715

Reputation: 5637

ruby on rails ajax fav button for posts

When a list of posts are generated, I want a logged in user to be able to click a star to favorite that post. Any suggestions on how to do this over ajax? I guess I would use a many_to_many relationship for this, but just not sure about posting over ajax in rails.

Upvotes: 1

Views: 529

Answers (1)

MrDanA
MrDanA

Reputation: 11647

First: your associations could be more explicit with a join table, like UserFavourites(user_id, post_id), and do:

# user.rb
has_many :user_favourites
has_many :favourites, :through => :user_favourites, :class_name => "Post"

Then in your views you could create a favourites link (the star image) and let's say that that link had an ID of favourite. Then you could use jQuery (or whatever) and do:

$("#favourite").click(function() {
    $.ajax({
        url: "/users/add_favourite",
        data: {some_data_you_may_want_to_send: the_data},
        success: function(html){
            //do something here if you want
        }
    });
});

This will require some controller action in Users called add_favourite, and you can have it return some HTML or return nothing and just add the favourite to the user.

Upvotes: 2

Related Questions