When working on my Rails project, I encountered an issue with adding data to the database using `http.post` from an AngularJS controller. Below is the code snippet demonstrating 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>
The code snippet in the Rails project looks like this:
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
After completing the text field and posting data to the Rails project, the data is not added to the database until the page is refreshed. How can I achieve adding new data to the database and displaying it on index.html without reloading the page? Is the issue in the Rails controller or the AngularJS code?
By setting a unique validation for restaurant name, sending a name that already exists in the database prevents the data from being added by the Rails controller. How can I capture the error generated by Rails and display it to the user in the AngularJS HTML code?
Note
: I use an external view for AngularJS, store templates in the public folder, and then route the URL using `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'
})
])