【发布时间】:2012-08-08 08:37:31
【问题描述】:
我有一个网络服务,它接收来自另一台服务器的传入 POST 请求。请求的字段映射到我的 rails 应用程序中名为“消息”的模型。
当我发送 JSON POST 时
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d
'{"message":{"content":"GUESTTEST","time":"2012-08-01 10:30:99","businessNumber":"5555","sessionId":"5555CHS1343808543654"}}'
http://localhost:3000/messages.json
请求被块处理:
respond_to do |format|
if @message.save
format.html { redirect_to @message, notice: 'Message was successfully created.' }
format.json { render json: @message, status: :created, location: @message }
end
并且对象保存成功。
很遗憾,我从其他 Web 服务收到的 POST 请求不是 json 格式,格式如下:
content=GUESTTEST&time=2012-08-01+10%3A09%3A03&businessNumber=5555&sessionId=5555CHS1343808543654
如何编写自己的路由和方法来处理这些请求并将它们映射到我的消息模型?
任何提示将不胜感激!
===== 更新:
我已经通过在控制器中基于顶级参数元素创建对象来解决这个问题,如下所示:
def create
@message = Message.new(content: params[:content], command: params[:command], messageId: params[:messageId], msisdn: params[:msisdn], businessNumber: params[:businessNumber], keyword: params[:keyword], operatorCode: params[:operatorCode], sessionId: params[:sessionId], time: params[:time])
respond_to do |format|
if @message.save
format.html { redirect_to @message, notice: 'Message was successfully created.' }
format.json { render json: @message, status: :created, location: @message }
else
format.html { render action: "new" }
format.json { render json: @message.errors, status: :unprocessable_entity }
end
end
结束
什么是更优雅的方式来实现这一点?
【问题讨论】:
标签: ruby-on-rails json http-post