I'm trying to register using Angularjs, but I want to get the validations that are in my model in rails. But I'm having trouble:
Covenat (model) Rails
validates :name, presence: true
Covenat Action Create controller
def create
@covenat = Covenat.new(covenat_params)
if @covenat.save
render json: @covenat, status: 200
else
render json: { errors: @covenat.errors }, status: 422
end
end
view /assets/templates/covenats/new.html
<form name="form" ng-submit="submit()" novalidate>
<div class="form-group" ng-class="errorClass('name')">
<label class="control-label" for="covenat_name">Nome</label>
<input class='form-control' type='text' ng-model='covenat.name' name='covenat_name' id="covenat_name" required/>
<p class="help-block" ng-show="form.name.$invalid && form.name.$dirty">
{{ errorMessage('name')}}
</p>
</div>
</form>
covenats_new_controller.js
angular.module('clinica')
.controller('CovenatsNewCtrl', ['$scope', 'Covenat', '$location',
function($scope, Covenat, $location){
$scope.submit = function() {
console.log("submit")
function success(response) {
console.log("success", response)
$location.path("/covenats");
}
function failure(response) {
console.log("failure", response)
_.each(response.data, function(errors, key) {
_.each(errors, function(e) {
$scope.form[key].$dirty = true;
$scope.form[key].$setValidity(e, false);
});
});
}
Covenat.save($scope.covenat, success, failure);
};
$scope.errorClass = function(name) {
var s = $scope.form[name];
return s.$invalid && s.$dirty ? "error" : "";
};
$scope.errorMessage = function(name) {
var s = $scope.form[name].$error;
result = [];
_.each(s, function(key, value) {
result.push(value);
});
return result.join(", ");
};
}]);
I have the following error in function failure:
TypeError: Can not read property '$ invalid' of undefined
in line return s.$invalid && s.$dirty ? "error" : "";