5

I am sending HTTP POST request:

data = { id: 1, name: 'ABC' }

uri = URI.parse('http://localhost:3000/events')
http = Net::HTTP.new(uri.host, uri.port)
http.post(uri, data.to_json)

My routes file:

Rails.application.routes.draw do
  post '/events' => 'receiver#create'
end

Whereas create methods looks like:

def create
 package = {
  id: ,
  name: 
 }
end

How can I get access to data values passing via request? My goal is to assign it to new hash within create method

5
  • Have you tried params[:id] and params[:name]? Commented Aug 5, 2015 at 8:02
  • yes but I get 422 status Commented Aug 5, 2015 at 8:04
  • Could you try to change in your sending script to: data = { package: { id: 1, name: 'ABC' } }, and in your controller try to access it simply with params[:package]? Commented Aug 5, 2015 at 8:13
  • you should turn off CSRF token in controller and try again. protect_from_forgery :except => :create Commented Aug 5, 2015 at 8:26
  • I dont know how to solve it still Commented Aug 5, 2015 at 8:55

1 Answer 1

3

You should set Content-Type header in your request as well:

http.post(uri, data.to_json, {"Content-Type" => "application/json", "Accept" => "application/json"})

Then you can use params[:id] and params[:data] in your controller.

def create
  @package = {id: params.require(:id), data: params.require(:data)}
  head :no_content
end

head :no_content will render empty reply (so you can create view later). And params.require will ensure that your parameters is provided (otherwise controller will return 400 Bad Request response) – so you won't receive some strange undefined method ... of nil errors later in case you missed params in your request.

Sign up to request clarification or add additional context in comments.

6 Comments

Sure. What exactly do you want to do with that data from request?
create a new hash and assign values from params to specified keys within my new hash
status 200 and then I can create a new view and display there that hash
now I get: Started POST "/events" for 127.0.0.1 at 2015-08-05 11:12:22 +0200 Processing by ReceiverController#create_package as JSON Parameters: {"id"=>1, "name"=>"ABC", "receiver"=>{"id"=>1, "name"=>"ABC"}} Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.0ms) ActionView::MissingTemplate (Missing template receiver/create_package, application/create_package with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :slim, :coffee, :jbuilder]}.
Well, that's because you need to first create a new view. Or you could add head :no_content to the end of your controller to render empty response.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.