开发者

Write Web call for iphone in ruby on rail. I want to get json formate and send response but formate of json is incorrect

I have a bug in the following Rails code which I cannot find. Any help would be appreciated.

class Api::ItemsController < ApplicationController
  respond_to :json

  def crea开发者_如何学编程te
    begin
      #puts "params: #{params}"

      if params[:item_post][:user][:uid] && params[:item_post][:user][:provider]
        @user = User.find_by_provider_and_uid(params[:item_post][:user][:provider], params[:item_post][:user][:uid])
      elsif params[:item_post][:user][:token]
        @user = User.create_with_token(params[:item_post][:user][:token])
      elsif params[:item_post][:user][:email]
        @user = User.find_by_email(params[:item_post][:user][:email])
      end

      if @user
        @item = @user.items.new(params[:item_post][:item])
      else
        @item = Item.new(params[:item_post][:item])
        @item.reply_email = params[:item_post][:user][:email]
      end

      if @item.save
        if params[:item_post][:item_images]
          params[:item_post][:item_images].each_value do |item_image|
            @item.images.create(item_image)
          end
        end
        respond_with(@item)
      else
        #puts "Errors 1: #{@item.errors}"
        respond_with(@item.errors)
      end


    rescue => e
      #puts "Errors 2: #{e.message}"
      respond_with(e.message.to_json, :status => :unprocessable_entity)
    end
  end

end

Problem:

I have been looking into the parameters received by the server. And I've tried to find the code where the parameters are built. Where can I find it?

In the server logs I can see the post as:

{"item_post":"{\"item\":{\"title\":\"Apple TV\",\"price\":\"45.50\",\"description\":\"Dual-Shielded High Speed HDMI Cable with Ethernet 2M are sold yesterday\",\"zipcode\":\"94102\"},\"user\":{\"email\":\"user@email.com\"}}}

I was expecting the post to look like this:

{\"item_post\":{\"item\":{\"title\":\"Apple TV\",\"price\":\"45.50\",\"description\":\"Dual-Shielded High Speed HDMI Cable with Ethernet 2M are sold yesterday\",\"zipcode\":\"94102\"},\"user\":{\"email\":\"user@email.com\"}}}

It seems to me that the 'item_post' block is being wrapped in unnecessary quotes, making it a string instead of a JSON hash:

I think this:

{"item_post":"{

should look like (no quote) this:

{"item_post":{

I am only guessing to what the problem could be.


I think you need avoid the to_json in your rescue

respond_with(e.message.to_json, :status => :unprocessable_entity)

put

respond_with(e.message, :status => :unprocessable_entity)

In your case the to_json before the to_json in the respond_with return a String it's why you have a String convert in JSON and not your Hash convert in JSON

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜