Reputation: 225
I created a simple API with Ruby on Rails,and I'm trying to send data from a form with AngularJS. The thing is that the App is sending the post method and the backend is creating the new records, so far it's working, but it creates it with Null values.
This is the form:
<div ng-controller="postController">
<form name="messageForm" ng-submit="submitForm()">
<div class="form-group">
<label>Name</label>
<input type="text" name="content" class="form-control" ng-model="message.content">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
This is the Angular Controller:
app.controller('postController', function($scope, $http) {
// create a blank object to handle form data.
$scope.message = {};
// calling our submit function.
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:3000/api/v1/messages',
data : $scope.message, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
// Showing errors.
$scope.errorContent = data.errors.errorContent;
} else {
$scope.message = data.message;
}
});
};
});
And in the RoR's API Controller, this is the Create method:
def create
respond_with Message.create(params[:message])
end
The only rows are:
Upvotes: 1
Views: 1025
Reputation: 1264
You must assign a key to your message
object in data
parameter, like this:
$http({
method : 'POST',
url : 'http://localhost:3000/api/v1/messages',
data : { data: $scope.message },
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.sucess(function(data){ ... });
And then, in your controller:
def create
respond_with Message.create(params[:data])
end
Hope this help :)
Upvotes: 2