我正在尝试为书店项目设置Rails API后端,前端将做出反应。后端目前只有一个模型,即Book模型。在前端的中,我将根据书籍的类别过滤书籍。我想在后端设置过滤条件,以便在前端选择下拉菜单时,仅显示适合特定类别的图书。到目前为止,这里是后端的内容:
书籍型号
class Book < ApplicationRecord
validates :title, :category, presence: true
scope :categorized, -> (category) { where("category LIKE ?", "#{category}" ) }
end
我的图书控制者看起来像这样:
Book controller
class Api::V1::BooksController < Api::V1::ApiController
before_action :set_book, only: %i[show update destroy]
def index
@books = Book.all
render json: @books
end
def categorized
@category = params[:book]
@books = Book.categorized(@category)
render json: @books
end
def show
render json: @book
end
def create
@book = Book.new(book_params)
if @book.save
render json: @book, status: :created
else
render json: @book.errors, status: :unprocessable_entity
end
end
def update
if @book.update(book_params)
render json: @book
else
render json: @book.errors, status: :unprocessable_entity
end
end
def destroy
@book.destroy
end
private
def set_book
@book = Book.find(params[:id])
end
def book_params
params.require(:book).permit(:title, :category)
end
结束
Routes.rb
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :books do
collection do
get :categorized
end
end
end
end
结束
样本数据
这里是查询数据库中所有书籍时从API获取的示例数据:
[
{
"id": 1,
"title": "I Know Why the Caged Bird Sings",
"category": "Fable"
},
{
"id": 2,
"title": "His Dark Materials",
"category": "Speech"
},
{
"id": 3,
"title": "To Say Nothing of the Dog",
"category": "Fable"
},
{
"id": 4,
"title": "An Acceptable Time",
"category": "Science fiction"
},
{
"id": 5,
"title": "A Scanner Darkly",
"category": "Suspense/Thriller"
},
{
"id": 6,
"title": "The Golden Bowl",
"category": "Science fiction"
}
]
[我的兴趣是我只想看“科幻小说”书籍或我只选择的其他任何类别使用范围。类别不限于示例数据中显示的内容;夸大他们可能会增加。我在模型中上面的配置没有得到我所需要的需要。使用邮递员时,没有任何结果。我得到的最好是一个空数组。
scope:categorized,->(category){where(“ category LIKE?”,“#{category}”)}]
您确定只需要一个地方使用此示波器吗?为什么不仅仅过滤控制器?第二个想法是使用Book.where(category:category),它将产生“ WHERE CATEGORY =?”而不是“在哪里分类”第三-也许您可以摆脱分类路线而仅将index与可选参数一起使用?您也可以稍后在索引控制器中添加分页-其中... page(page).per(per)第四,有一个很好的做法,是使用实例变量访问器方法代替变量本身:
def set_book@book = Book.find(params [:id])结束
收件人
定义书@book || = Book.find(params [:id])结束
另外,find方法也会引发异常。您可能想在课堂上从中解脱。您也可以使用book.update!并保存!并从其他方法中解救出来-那么您将不需要这些if / else分支。