我們有一個要求,即用戶需要爲他們的個人資料選擇他們的虛擬形象。在編輯個人資料頁面上,用戶點擊一個更改圖片鏈接,將他們帶到另一個頁面,並給他們提供兩個鏈接,從Facebook或Gravatar獲取他們的照片。此頁面上還顯示圖像預覽,以及保存按鈕。該頁面的控制器是AvatarsController。我已經編輯和更新動作,以及針對Facebook和gravatar的自定義GET動作,以便該路線看起來像是頭像/臉譜和頭像/頭像。這些操作只需查詢相應的服務,然後創建一個包含照片網址的新頭像模型。當用戶單擊保存時,將調用更新操作,並將頭像模型與配置文件一起保存。該頁面由編輯模板傳送,因爲默認情況下,當創建用戶時,還會創建空頭像。有關爲軌道中的虛擬形象選擇場景構建RESTful資源的建議
的剖面模型(使用mongoid)基本上看起來像:
def Profile
embeds_one :avatar
end
和化身模型看起來像:
def Avatar
embedded_in :profile
end
路徑看起來像:
resource :avatar, only: [:edit, :update] do
member do
get 'facebook'
get 'gravatar'
end
end
控制器看起來像:
class AvatarsController < ApplicationController
def facebook
url = AvatarServices.facebook(current_user, params[:code])
respond_to do |format|
unless url
format.json { head :no_content }
else
@avatar = Avatar.new({:url => url, :source => "Facebook"})
@avatar.member_profile = current_user.member_profile
format.html { render :edit }
format.json { render json: @avatar }
end
end
end
def gravatar
respond_to do |format|
url = AvatarServices.gravatar(current_user)
unless url
format.json { head :no_content }
else
@avatar = Avatar.new({:url => url, :source => "Gravatar"})
@avatar.member_profile = current_user.member_profile
format.html { render :edit }
format.json { render json: @avatar }
end
end
end
def edit
@avatar = current_user.member_profile.avatar
end
def update
@avatar = current_user.member_profile.avatar
respond_to do |format|
if @avatar.update_attributes(params[:avatar])
format.html { redirect_to edit_member_profile_path }
format.json { head :no_content }
else
format.html
format.json { render json: @avatar.errors }
end
end
end
end
這工作,但作爲相當新的軌道,我想知道,如果鐵軌專家會設立的Facebook'和'的gravatar的資源不同,或許更RESTful的方式?
剛剛添加了控制器。我也在思考同樣的問題,每個服務都有一個控制器。但後來我認爲facebook和gravatar圖片仍然屬於用戶的頭像資源,只是他們只是從外部服務中查詢。 – stantona 2012-04-24 15:33:02