2017-08-19 153 views
0

我想要在軌數據庫中獲取的數據,這是我的控制器文件軌500內部服務器錯誤

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' } 
+0

你能否提供更多關於錯誤的細節? –

回答

1

你應該在這種情況下做的第一件事是諮詢你的控制檯或日誌;這將對查明異常情況最有幫助。

這麼說,我會採取一種猜測,並保證該問題是,你調用一個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 
+0

日誌: ActionView :: MissingTemplate(Missing template paths/getall,application/getall with {:locale => [:en],::formats => [:html,:text,:js,:css,:ics,: csv,:vcf,:png,:jpeg,:gif,:bmp,:tiff,:mpeg,:xml,:rss,:atom,:yaml,:multipart_form,:url_encoded_form,:json,:pdf,搜索: *「C:/ Users/Ali Ammar/Web:警察/警察/應用/視圖「 *」C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/devise-4.2.0/app/views「 ): –

+0

這是一個問題使用'respond_to',因爲它沒有在你的動作中定義,rails會默認尋找一個模板來呈現響應。 –

+0

那麼如何解決它? –

0

讓我們提高您的代碼有點:

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,如果數據庫中沒有記錄)

+0

爲空集合返回404對我來說似乎很奇怪。這對於單個項目「GET/paths/1」是有意義的,但它是完全有效和清晰的(恕我直言)以擁有一個空的結果集。考慮到這是一個頁面加載,你不會404用戶訪問「路徑/全部」頁面,你只是告訴他們,目前沒有路徑(他們會不會添加一個?)。 –

+0

您也可以選擇帶有空載荷的200。但不要混淆,服務器的響應將不得不由你的JS代碼來管理。因此,處理錯誤仍然需要傳播到UI。如果你有一個404,你只需要捕獲這個錯誤並向用戶顯示正確的信息,比如創建一條新記錄。 –

+0

JSON狀態碼(google)https://cloud.google.com/storage/docs/json_api/v1/status-codes在這種情況下,他們會使用404 –