我试图点击服务器以返回类别的category_scores。现在,当我尝试点击服务器时,它会在控制台中给我一个错误:
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
CATEGORY
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
CATEGORY SCORES
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
我在路线文件中添加了一条自定义路线:
路线
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");
})
})
});
以下是rails控制台的错误:
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 :(得分:1)
我认为您需要定义category
。
class CategoriesController < ApplicationController
def scores
category = Category.find(params[:category_id])
render json: category.category_scores.all, status: :ok
end
end