抓住json送到铁轨

时间:2015-06-10 18:17:50

标签: ruby-on-rails json ruby-on-rails-4

我有一个命令发布到某个json的rails url:

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d ' {"user":{"first_name":"firstname","last_name":"lastname","email":"email@email.com","password":"app123","password_confirmation":"app123"}}'  http://localhost:3000/maps

我在我的控制器中创建了一个方法:

def create
    #@map = Map.new(map_params)
    #@json = ActiveSupport::JSON.decode(open('jsonfeed').read)
    @result = JSON.parse string #parse json, but where to get that json first
    respond_to do |format|
      if @map.save
        format.json {
          #render :show, status: :created, location: @map
        }
      else
        format.json { render json: @map.errors, status: :unprocessable_entity }
      end
    end
  end

如何将json发送到rails。我thinsk JSON.parse将解析我的json并返回hash参数,但首先是如何获取json。

1 个答案:

答案 0 :(得分:1)

在控制器中添加以下代码并尝试。

before_action :parse_json_data_to_params, except: [ # Put Your Get Actions Names Here otherwise it will raise error for get requests ]

def parse_json_data_to_params
  params.merge!(ActiveSupport::JSON.decode(request.raw_post))
end