Reputation: 1944
Im working on Rails + AngularJS app. In order to access json response of my app I have to /something.json
in my angular $resource url instead of just /something
is there a way how to fix it?
Routes
upvote_post_comment PUT /posts/:post_id/comments/:id/upvote(.:format) comments#upvote
post_comments POST /posts/:post_id/comments(.:format) comments#create
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
upvote_post PUT /posts/:id/upvote(.:format) posts#upvote
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
post GET /posts/:id(.:format) posts#show
GET / home#index
PostsController
class PostsController < ApplicationController
def index
@posts = Post.all
respond_to do |format|
format.json { render json: @posts }
end
end
end
Angular serviceProvider
angular.module('flapperNews')
.factory('posts', ['$resource', function($resource) {
return $resource('/posts.json/:id', {id: "@id"})
}]);
Upvotes: 0
Views: 813
Reputation: 355
Set default format in routes.rb
resources :posts, defaults: { format: :json }
Upvotes: 2
Reputation: 694
In your controller you are saying by respond_do
to give a json response only when the format (.:format) in the routes
is specified as json.
You can modify your controller PostsController to respond with json no-matter-what the format is.
class PostsController < ApplicationController
def index
@posts = Post.all
render json: @posts
end
end
Note: After this the format after the url wouldn't matter (be it .json, .xml, nothing). The controller's action wold always return json.
Upvotes: 1
Reputation: 4861
Try adding .json
to the end of the URL
angular.module('flapperNews')
.factory('posts', ['$resource', function($resource) {
return $resource('/posts/' + id + '.json')
}]);
Upvotes: 1