我試圖在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中傳遞的值,並改變它們。
在此先感謝。
就是這樣。感謝有關如何使用它並進行測試的解釋。我使用了第二種格式。 –
很高興聽到@BartC –