开发者

ruby on rails ajax fav button for posts

开发者 https://www.devze.com 2023-03-24 00:56 出处:网络
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

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

精彩评论

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