2011-02-08 26 views
2

假設我有一個顯示視頻的Rails 3應用程序。用戶可以「喜歡」或「不喜歡」視頻。另外,他們可以喜歡/不喜歡其他的東西,比如遊戲。我需要一些總體設計方面的幫助,以及如何處理RESTful路線。什麼是適合REST的方式來「喜歡」Rails 3中的某些東西?

目前,我有一個使用多形設計,使對象是 「可愛」(likeable_id,likeable_type)

我想通過AJAX(jQuery的1.5)做這個Like Class。所以,我在想是這樣的:

的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)。

任何建議,將不勝感激。

+0

我正在關閉這個,因爲我已經更簡化了代碼。現在我發佈了針對遊戲和視頻的「/ likes/it」。感謝您的信息。 – cbmeeks 2011-02-09 11:56:30

回答

2

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. 

而PUT:該封閉實體所提供的請求URI下儲存

請求。如果Request-URI指向一個已經存在的資源,那麼封閉的實體應該被認爲是駐留在原始服務器上的修改版本。

您的功能屬於哪個類別取決於您 - 只要您與自己保持一致即可。

+0

爲了記錄,絕對不要使用GET來獲取這樣的資源,因爲網絡爬蟲可能會嘗試「獲取」URL並導致不喜歡/喜歡某事:) – 2014-11-18 07:18:51

相關問題