【问题标题】:What is the proper RESTful way to "like" something in Rails 3?在 Rails 3 中“喜欢”某些东西的正确 RESTful 方式是什么?
【发布时间】:2011-02-08 21:30:19
【问题描述】:

假设我有一个显示视频的 Rails 3 应用。用户可以“喜欢”或“不喜欢”视频。此外,他们可以喜欢/不喜欢游戏等其他事物。在整体设计以及如何处理 RESTful 路由方面,我需要一些帮助。

目前,我有一个 Like Class 使用多态设计,以便对象是“可喜欢的”(likeable_id,likeable_type)

我想通过 AJAX (jQuery 1.5) 做到这一点。所以我在想这样的事情:

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",
        ....
    });
} );

导轨控制器

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

路线

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

这个逻辑看起来正确吗?我正在通过 AJAX 进行 POST。从技术上讲,我不应该做 PUT 吗?还是我太挑剔了?

另外,我的控制器使用非标准动词。喜欢videogame。我应该担心吗?有时我对如何匹配“正确”动词感到困惑。

另一种方法是使用包含类型(游戏或视频)的数据结构发布到 /likes/:id 之类的内容。然后我可以将它包装在控制器中的一个动词中......甚至可能是更新(PUT)。

任何建议将不胜感激。

【问题讨论】:

  • 我将关闭它,因为我已经进一步简化了代码。我现在为游戏和视频发布到“/likes/it”。感谢您提供信息。

标签: ruby-on-rails-3 rest jquery


【解决方案1】:

Rest architectural style 没有指定你应该使用哪个“动词”。它只是说如果他们想要连接器,可以使用 HTTP。

您正在寻找的是HTTP specifications for method definitions。 POST 尤其适用于:

  - 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.

同时放置:

请求将封闭实体存储在提供的 Request-URI 下。如果 Request-URI 引用了一个已经存在的资源,封闭的实体应该被认为是源服务器上的一个修改版本。

您的功能属于哪个类别取决于您 - 只要您对此保持一致即可。

【讨论】:

  • 郑重声明,切勿将 GET 用于此类资源,因为网络爬虫可能会尝试“获取”URL 并导致不喜欢/喜欢某些内容:)
猜你喜欢
  • 2012-07-06
  • 1970-01-01
  • 2011-09-09
  • 2023-03-27
  • 1970-01-01
  • 2021-03-25
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多