开发者

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 开发者_如何学Pythonthis over ajax? I guess I would use a many_to_many relationship for this, but just not sure about posting over ajax in rails.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜