2014-10-30 86 views
1

我正在嘗試訪問服務器以傳回一個類別的category_scores。現在,當我嘗試打服務器,它給了我回來在控制檯中的錯誤:無法從Ruby on Rails獲取JSON Ajax調用

GET http://localhost:7000/categories/3/category_scores 500 (Internal Server Error) 

在主頁上,我已經通過Rails的一個選擇菜單,讓所有的類別。

<div id="category-select"> 
    <%= collection_select(:id, :name, @categories, :id, :name, prompt: "Select category") %> 
</div> 

爲了讓大家有更多的背景,這裏有一個類別和category_score模型

類別

class Category < ActiveRecord::Base 
    has_many :category_scores 

    validates :name, presence: true 

    include PgSearch 
    multisearchable against: :name 


    def as_json(data) 
    { 
     id: id, 
     gg: gg, 
     name: category.name 
    } 
    end 
end 

類別分數

class CategoryScore < ActiveRecord::Base 
    belongs_to :restaurant 
    belongs_to :category 
    has_many :items 

    scope :health_order, -> {order("category_scores.gg DESC")} 

    def as_json(data) 
    { 
     id: id, 
     gg: gg, 
     name: category.name 
    } 
    end 
end 

我添加了一個自定義路由到我的路線文件:

ROUTES

get 'categories/:category_id/category_scores', to: 'categories#scores' 

類別的控制器

class CategoriesController < ApplicationController 

    def scores 
    category = Category.find(params[:category_id]) 
    render json: category.category_scores.all, status: :ok 
    end 

end 

於是最後,這裏是我使用的嘗試,並擊中了服務器,以獲得JSON JavaScript的。我猜這沒有什麼錯,但是我在後端做的事情,因爲我無法讓JSON出現。現在當我console.log的categoryID,它確實顯示爲正確的,所以我不知道爲什麼它不通過控制器進行。

$(document).ready(function() { 
    var categorySelect = $("#category-select > select"); 

    categorySelect.on("change", function(event) { 
    var categoryId = parseInt($("#category-select option:selected").val(), 10); 
    console.log(categoryId) 

    $.get("/categories/" + categoryId + "/category_scores", function(data){ 
     console.log(success); 
     renderCategoryScores(data); // render category scores with this category ID 
    }) 
     .fail(function(){ 
     console.log("error"); 
     }) 
    }) 
}); 

下面是軌道控制檯中的錯誤:

Started GET "/categories/2/category_scores" for 127.0.0.1 at 2014-10-30 13:33:27 -0700 
Processing by CategoriesController#scores as */* 
    Parameters: {"category_id"=>"2"} 
Completed 500 Internal Server Error in 3ms 
** [Airbrake] Notice was not sent due to configuration:   
    Environment Monitored? false   
    API key set? false 

NameError (undefined local variable or method `category' for #<CategoriesController:0x007ff1040a6778>): 
    app/controllers/categories_controller.rb:4:in `scores' 
+0

你能否包含更多的錯誤回溯? – srt32 2014-10-30 20:32:31

+0

如果您發佈錯誤跟蹤並指明錯誤行是什麼,這將有所幫助。 – 2014-10-30 20:32:46

+0

剛剛添加了rails c錯誤。錯誤行以NameError開頭。 – LMo 2014-10-30 20:35:12

回答

1

我認爲你需要定義category

class CategoriesController < ApplicationController 

    def scores 
    category = Category.find(params[:category_id]) 
    render json: category.category_scores.all, status: :ok 
    end 

end