Reputation: 1
i'm trying to fetch data from database in rails, this is my controller file
class PathsController < ApplicationController
before_filter :authenticate_user!
skip_before_filter :verify_authenticity_token
def getall
@result = Path.select('x', 'y')
end
respond_to do |format|
format.json { render json: @result }
end
end
Here is my js function
function makelines()
{
$.ajax({
type: "GET",// => method type
url: "/path", // => Target function that will be return result
contentType:"application/json",
success: function(result){
result = JSON.parse(result);
console.log(result);
}
});
}
Here is the route
match '/path => 'Paths#getall', via: [:get, :post], :default => { :format => 'json' }
Upvotes: 0
Views: 2122
Reputation: 2344
Let's improve your code a little bit:
def getall
@results = Path.select('x', 'y')
respond_to do |format|
if @results.count > 0
format.json { render json: @results, , status: :ok }
else
format.json { render json: @results.errors, , status: :not_found }
end
end
end
Per Rails conventions it would be better to return results
instead of result
as you are returning more than 1 item.
I also think that as you are returning a JSON object to your AJAX method it would be good to return either a 200 (:ok) or a 404 (:not_found, in the event no record is in the database)
Upvotes: 0
Reputation: 29271
The first thing you should do in this circumstance is consult your console or logs; that will be the most helpful in pinpointing the exception.
That said, I'll take a guess and warrant that the issue is that you are invoking a respond_to
outside of a controller action
def getall
@result = Path.select('x', 'y')
end
respond_to do |format|
format.json { render json: @result }
end
Should be:
def getall
@result = Path.select('x', 'y')
respond_to do |format|
format.json { render json: @result }
end
end
Upvotes: 1