2010-07-23 175 views
0

我爲我的Rails 2.3 Web服務應用程序使用Inherited Resources。 這是一個偉大的圖書館,是Rails 3的一部分。Rails繼承資源使用情況

我想弄清楚輸出結果的最佳做法。

class Api::ItemsController < InheritedResources::Base 
    respond_to :xml, :json 
    def create 
    @error = nil 
    @error = not_authorized if [email protected] 
    @error = not_enough_data("item") if params[:item].nil? 

    @item = Item.new(params[:item]) 
    @item.user_id = @user.id 
    if [email protected] 
     @error = validation_error(@item.errors) 
    end 
    if [email protected]? 
     respond_with(@error) 
    else 
     respond_with(@swarm) 
    end 
    end 

end 

它在請求成功時工作良好。但是,如果出現任何錯誤,我會收到「模板不見」錯誤。 @error基本上是消息和狀態的散列,例如{:message => "Not authorized", :status => 401}。看起來respond_with只調用to_xmlto_json與控制器關聯的特定型號。

什麼是處理此問題的優雅方法? 我想避免創建(在這種情況下create.xml.erb和create.json.erb)對每個動作的模板文件,每種格式

基本上我想:提前

/create.json [POST] => {"name": "my name", "id":1} # when successful 
/create.json [POST] => {"message" => "Not authorized", "status" => 401} # when not authorized 

感謝。

回答

0

幾件事情,然後纔開始:

  • 第一關。這是Ruby。你知道有一個unless命令。你可以放下if !
  • 而且,你不必做的if !*.nil?雙重否定 - 做if *.present?
  • 你不需要通過使nil發起的變量。除非您將其設置爲before_chain,否則您將在以後的通話中覆蓋它。

你想要做的是使用render :json方法。檢查API,但它看起來是這樣的:

render :json => { :success => true, :user => @user.to_json(:only => [:name]) } 
0

授權應當實現回調(的before_filter),和其餘的代碼應該被刪除,並作爲繼承。只有輸出應該參數化。這裏有很多自定義代碼...