假设我有一个显示视频的 Rails 3 应用程序。用户可以“喜欢”或“不喜欢”视频。此外,他们还可以喜欢/不喜欢其他事物,例如游戏。我在整体设计以及如何处理 RESTful 路由方面需要一些帮助。
目前,我有一个 Like 类
,它使用多态设计,以便对象“讨人喜欢”(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",
....
});
} );
导轨 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
路线
match "/likes/video/:id" => "likes#video", :as => :likes_video
match "/likes/game/:id" => "likes#game", :as => :likes_game
这个逻辑看起来正确吗?我正在通过 AJAX 进行 POST。从技术上讲,我不应该做 PUT 吗?还是我对此太挑剔了?
此外,我的 Controller 使用非标准动词。例如视频
和游戏
。我应该担心这个吗?有时我对如何匹配“正确”动词感到困惑。
另一种方法是使用包含类型(游戏或视频)的数据结构发布到诸如 /likes/:id
之类的内容。然后我可以将其包装在 Controller 中的一个动词中......甚至可以更新(PUT)。
如有任何建议,我们将不胜感激。
最佳答案
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.
当放置时:
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.
您的功能属于哪个类别取决于您 - 只要您对此保持一致即可。
关于ruby-on-rails-3 - Rails 3 中 "like"的正确 RESTful 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4938693/