2016-02-29 33 views
0

我試圖在Rails 4應用程序中創建一個API以允許其他應用程序創建記錄。記錄是基於其他應用程序知道的內容創建的,但需要保存的實際數據有所不同。我需要在params被用來創建新記錄之前操縱params。Rails 4:如何在創建之前操作api控制器中的參數

我的模型:

class Product 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    field :prod_code, type: String 
    field :batch_id, type: BSON::ObjectId 
    field :assy_lot_id, type: BSON::ObjectId 
    field :assy_lot_sn, type: String 

    belongs_to :assy_lot 
    belongs_to :batch 
end 

API控制器

module Api 
    module V1 
    class ProductsController < ActionController::Base 
     before_filter :restrict_access 

     respond_to :json 

     def create 
     variant_id = Variant.find(variant: params[:product]["variant"]).first   
     assy_lot_id = AssyLot.find(assy_lot: params[:product]["assy_lot"],variant_id: variant_id).first 

     params[:product][:prod_code]=params[:product]["variant"] + "-" + params[:product]["assy_lot"] + "-" + params[:product]["assy_lot_sn"] 
     params[:product][:batch_id]=Batch.find(assy_lot_id: assy_lot_id).first 
     params[:product][:assy_lot_id]=assy_lot_id 

     params[:product].delete "variant"   

     respond_with Chip.create(params[:product]) 
     end 

    private 

     def restrict_access 
     authenticate_or_request_with_http_token do |token, options| 
      ApiKey.where(access_token: token).exists? 
     end 
     end 
    end 
    end 
end 

當我測試,捲曲

curl -v http://localhost:3000/api/v1/chips.json -H 'Authorization:Token token="xxxxxxxxx"' -X POST -d '{"variant":"NA","assy_lot":"004","assy_lot_sn":"0001"}' 

它連接OK的API,但我得到

undefined method `[]' for nil:NilClass 

任何線路,我嘗試訪問參數值像這樣params[:product]["something"]

有人可以請指點我正確的語法,這將允許我檢查在params中傳遞的值,並改變它們。

在此先感謝。

回答

1

您正在以錯誤的方式使用curl命令。要通過捲曲傳遞數據,你應該寫

curl -v http://localhost:3000/api/v1/chips.json -H 'Authorization:Token token="xxxxxxxxx"' -X POST -d "variant=NA&assy_lot=004&assy_lot_sn=0001" 

這將發送到PARAMS作爲軌道

{'variant': 'NA', 'assy_lot: 004', 'assy_lot_sn': '0001'} 

這將允許您訪問變量作爲params['variant']控制器內。

如果您想要在控制器中訪問變量params[:product]["variant"],則必須在curl命令中傳遞以下數據。

curl -v http://localhost:3000/api/v1/chips.json -H 'Authorization:Token token="xxxxxxxxx"' -X POST -d "product[variant]=NA&product[assy_lot]=004&product[assy_lot_sn]=0001" 
+0

就是這樣。感謝有關如何使用它並進行測試的解釋。我使用了第二種格式。 –

+0

很高興聽到@BartC –

1

您不應該使用「產品」參數發送請求嗎?試試這個:

curl -v http://localhost:3000/api/v1/chips.json -H 'Authorization:Token token="xxxxxxxxx"' -X POST -d 'product: {"variant":"NA","assy_lot":"004","assy_lot_sn":"0001"}' 
+0

應該這樣做 –

+0

謝謝。我肯定是以錯誤的方式使用捲曲,但也不知道如何正確獲取參數,即使我提交了它們也沒問題。 @羅漢的回答讓我走出了黑暗:D –

相關問題