0

I have the following route:

match '/curl_example' => 'people#curl_post_example', via: :post

In my controller:

class PeopleController < ApplicationController
  before_action :set_person, only: [:show, :edit, :update, :destroy]
  skip_before_action :verify_authenticity_token, :only => [:curl_post_example]
...
  def curl_post_example
    Person.create(request.body.read)
    render plain: "Thanks for sending a POST request with cURL! Payload: #{request.body.read}"
  end
...

I am trying to create a person via curl command with the following...

curl -X POST -d "{"first_name"=>"mista", "last_name"=>"wintas"}" http://localhost:3000/curl_example

When I do this I get this error at the console...

Started POST "/curl_example" for ::1 at 2016-11-08 13:24:46 -0500
Processing by PeopleController#curl_post_example as */*
  Parameters: {"{first_name"=>">mista, last_name=>wintas}"}
Completed 500 Internal Server Error in 0ms (ActiveRecord: 0.0ms)



ArgumentError (When assigning attributes, you must pass a hash as an argument.):

Looks like a hash to to me? What am I missing?

Mark Locklear
  • 5,044
  • 1
  • 51
  • 81
  • try passing `Person.create(params)` instead of `Person.create(request.body.read)` – mr_sudaca Nov 08 '16 at 18:34
  • I get the error `ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):` using params. If I pass in person_params I do get a bit farther with the error `ActionController::ParameterMissing (param is missing or the value is empty: person):` Furthermore, If I pass in `curl -X POST -d ""person"=>{"first_name"=>"mista", "last_name"=>"wintas"}" http://localhost:3000/curl_example` I get the error `NoMethodError (undefined method `permit' for ">{first_name=>mista, last_name=>wintas}":String` – Mark Locklear Nov 08 '16 at 18:47

1 Answers1

1

you need to pass params like this:

 curl -d "person[first_name]=john" -d "person[last_name]=doe" 

source: curl command line

and then, in your controller:

private def person_params
  params.require(:person).permit(:first_name, :last_name)
end

and call person_params instead of params in Person.create...

mr_sudaca
  • 1,156
  • 7
  • 9
  • With the code above I get the error `ActionController::ParameterMissing (param is missing or the value is empty: person):` – Mark Locklear Nov 08 '16 at 19:01
  • 1
    you need to pass params like this `curl -d "person[first_name]=john" -d "person[last_name]=doe" ` source: http://stackoverflow.com/questions/5826690/curl-command-line-post – mr_sudaca Nov 08 '16 at 19:03
  • Sweetness. Thanks dude. If you want to edit your answer above I will accept it. – Mark Locklear Nov 08 '16 at 19:06