3

I'm having some problems posting JSON data to my rails controller and getting the fields from my JSON data to map onto the paremeters to create my entity.

Here's what the action looks like:

def create
  @trip = Trip.new(params[:trip])
  if @trip.save
    respond_to do |format|
      format.json{render :json => @trip, :status => :created, :location => @trip }
    end
  end
end

And here's the output from the web server:

Started POST "/trips.json" for 127.0.0.1 at Sat Sep 03 12:37:41 -0400 2011
  Processing by TripsController#create as JSON
  Parameters: {"title"=>"Charlie"}
  AREL (0.5ms)  INSERT INTO "trips" ("created_at", "updated_at", "title") VALUES ('2011-09-03 16:37:41.945743', '2011-09-03 16:37:41.945743', NULL)
Completed 201 Created in 15ms (Views: 3.5ms | ActiveRecord: 0.5ms)

As you can see it's inserting NULL into the title field, I was expecting it to map it on from the JSON data?

Here's the HTTP request:

Host    localhost:3000
User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:6.0.1) Gecko/20100101 Firefox/6.0.1
Accept  */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection  keep-alive
Content-Type    application/json; charset=UTF-8
X-Requested-With    XMLHttpRequest
Referer http://localhost:3000/trips/new
Content-Length  19
Cookie  _tripplanner_session=BAh7ByIQX2NzcmZfdG9rZW4iMWJCVDc0YWNIeHROcmw5VC9ZVEhMdFNlR0dtTWtSVytCL0dwTi9yam1CUUU9Ig9zZXNzaW9uX2lkIiU1NzhlMDAwNmM2N2RkMTE1YTA3M2ZmMzA4NDQ0M2NmOQ%3D%3D--1c2f1fc1d7c1bd147fa1cf9cff47e77c050f51be
Pragma  no-cache
Cache-Control   no-cache

1 Answer 1

16

Your problem is that your controller is expecting parameters related to a trip to be in params[:trip].

Change your json to be

trip: {
  title: 'Charlie'
}

and I think that will fix it for you.

i.e. your params should look like params => {:trip => {:title => 'Charlie}}

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.