In a rails project, I add data to database by http.post
from angularjs controller. I have below code to do this:
RestaurantIndexCtrl.js.coffee
:
restauranteur.controller 'RestaurantIndexCtrl', ['$scope', '$location', '$http', ($scope, $location, $http) ->
$scope.restaurants = []
$http.get('./restaurants.json').success((data) ->
$scope.restaurants = data
)
$scope.addRestaurant = (test) ->
$http({
url: '/restaurants#create',
method: "POST",
data: JSON.stringify({name:test}),
headers: {'Content-Type': 'application/json'}
})
]
templates/restaurants/index.html
:
<form ng-submit="addRestaurant(restaurant.name)">
<input type="text" ng-model="restaurant.name">
<button>Register</button>
</form>
<ul ng-repeat="restaurant in restaurants">
<li><a ng-click="viewRestaurant(restaurant.id)">{{ restaurant.name }}</a></li>
</ul>
And below code in rails project:
restaurants_controller.rb
:
def create
@restaurant = Restaurant.new(restaurant_params)
respond_to do |format|
if @restaurant.save
format.html { redirect_to @restaurant, notice: 'Restaurant was successfully created.' }
format.json { render action: 'show', status: :created, location: @restaurant }
else
format.html { render action: 'new' }
format.json { render json: @restaurant.errors, status: :unprocessable_entity }
end
end
end
Now, when I comlete the textfield
and post data to rails project, data aren't add to database until I refresh the page. When I refresh, data is add to database and show data on index.html
.
I want when I copmlete the
textfield
and post to rails controller by angularjs, new data are add to database and show onindex.html
without reloding. How can I do this? The problem is exist in rails controller or angularjs code?I set
unique validation
forrestaurant name
, now if I send a name that exist in database, rails controller doesn't permit to add data to database. How can I get error that rails generate and show to user inangularjs
html code?
Note
: I use external view for angularjs and put templates in public
folder and then route the url by ngRoute
.
main.js.coffee
:
@restauranteur = angular.module('restauranteur', ['ngRoute'])
@restauranteur.config(['$routeProvider', ($routeProvider) ->
$routeProvider
.when('/restaurants', {
templateUrl: '../templates/restaurants/index.html',
controller: 'RestaurantIndexCtrl'
})
.otherwise({
templateUrl: '../templates/home.html',
controller: 'HomeCtrl'
})
])