Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a rails app which works as an api, here my controller:

class CarController < ApplicationController
  def create
    @car = Car.new(params[:car])
    if @car.save
      render json: @car, status: :created, location: @car
    else
      render json: @car.errors, status: :unprocessable_entity
    end
  end
end

I want to "call" this create function from my angular app, here my angular factory

angular_app.factory('api', function($http) {
    $http.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

    return {
   //car looks like {owner:'Andres', year:'2014', ....} with every field of Car model
            SaveCar: function(car) {
                return $http.post('/car/', {car:car}).then(function(result) {
                    return result;
                })
            }
        }
});

The problem is that in my create car function I get someting like this:

{"{\"car\":{\"owner\":\"andres\",\"year\":\"2014\",....}}"=>nil, "action"=>"create", "controller"=>"car"}

just an string, and it should be:

{"car" => {"owner"=>"andres", "year":"2014", ....}, "action"=>"create", "controller"=>"task"}

What is my mistake here? I tried to use JSON.parse but didn't work.

share|improve this question
    
Maybe problem in strong parameters. So instead of params[:car] use params.require(:car).permit!. But it throw another error in this case. All seems ok. Except there is no routes for this request. –  zishe May 27 '14 at 23:33
    
@zishe tried that and got ActionController::ParameterMissing (param is missing or the value is empty: car): –  Andres May 27 '14 at 23:36
    
Perhaps that car in angular part is a string, not object. log it. –  zishe May 27 '14 at 23:39
    
string? I created as follow: var car = {owner:"Andres", year:"2014", ....} –  Andres May 27 '14 at 23:41
1  
@zishe got it, thanks for your help, if you find a better approach just answer. –  Andres May 28 '14 at 1:16

1 Answer 1

up vote 0 down vote accepted

Got it:

def create
    @car = Car.new(JSON.parse(request.body.read)['car'])

    if @car.save
        render json: @car, status: :created, location: @car
    else
        render json: @car.errors, status: :unprocessable_entity
    end
end

It works, but I don't really know what request.body.read does. Feel free to edit it and explain(remember, I'm starting with ruby)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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