[英]rails 500 internal server error
我正在尝试从Rails的数据库中获取数据,这是我的控制器文件
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
这是我的js功能
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);
}
});
}
这是路线
match '/path => 'Paths#getall', via: [:get, :post], :default => { :format => 'json' }
在这种情况下,您应该做的第一件事就是查阅控制台或日志; 这将对查明异常最有帮助。
也就是说,我会猜测并保证问题是您在控制器动作之外调用了respond_to
def getall
@result = Path.select('x', 'y')
end
respond_to do |format|
format.json { render json: @result }
end
应该:
def getall
@result = Path.select('x', 'y')
respond_to do |format|
format.json { render json: @result }
end
end
让我们改善一下代码:
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
根据Rails约定,最好返回results
而不是result
因为您要返回多个项目。
我还认为,当您将JSON对象返回到AJAX方法时,最好返回200(:ok)或404(:not_found,如果数据库中没有记录)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.