开发者

What is the proper RESTful way to "like" something in Rails 3?

Let's say I have a Rails 3 app that displays videos. The user can "Like" or "Dislike" the videos. Also, they can like/dislike other things like games. I need some help in the overall design and how to handle the RESTful routes.

Currently, I have a Like Class that uses polymorphic design so that objects are "likeable"开发者_开发技巧 (likeable_id, likeable_type)

I want to do this via AJAX (jQuery 1.5). So I was thinking something like:

javascript

// these are toggle buttons
$("likeVideo").click( function() {
    $.ajax({
        url: "/likes/video/" + video_id,
        method: "POST",
        ....
    });
} );

$("likeGame").click( function() {
    $.ajax({
        url: "/likes/game/" + game_id,
        method: "POST",
        ....
    });
} );

rails controller

Class Likes < ApplicationController
    def video
        # so that if you liked it before, you now DON'T LIKE it so change to -1
        # or if you DIDN'T like it before, you now LIKE IT so change to 1
        # do a "find_or_create_by..." and return JSON
        # the JSON returned will notify JS if you now like or dislike so that the 
        # button can be changed to match
    end

    def game
        # same logic as above
    end
end

Routes

match "/likes/video/:id" => "likes#video", :as => :likes_video
match "/likes/game/:id" => "likes#game", :as => :likes_game

Does this logic seem correct? I am doing a POST via AJAX. Technically, shouldn't I be doing a PUT? Or am I being too picky over that?

Also, my controller uses non-standard verbs. Like video and game. Should I worry about that? Sometimes I get confused on how to match up the "correct" verbs.

An alternative would be to post to something like /likes/:id with a data structure that contains the type (game or video). Then I could wrap that in one verb in the controller...maybe even Update (PUT).

Any suggestions would be appreciated.


Rest architectural style does not specify which "verb" you should be using for what. It simply says that one can use HTTP if they want to for connectors.

What you are looking for is HTTP specifications for method definitions. In particular POST is intended for:

  - Annotation of existing resources;
  - Posting a message to a bulletin board, newsgroup, mailing list,
    or similar group of articles;
  - Providing a block of data, such as the result of submitting a
    form, to a data-handling process;
  - Extending a database through an append operation.

while PUT:

requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.

Which category your functionality falls into is up to you - as long as you are consistent with yourself about it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜