Book.all Actiong 显示 []

问题描述 投票:0回答:1

我是 Ruby On Rails 开发新手,我正在构建一个包含类 user 的 API,
书、作者和书架。当我调用 Book.all 检索数据库中的所有书籍时,我得到 [] 作为回报,但不知道可能是什么问题。以下是书籍迁移、书籍模型和书籍控制器文件:

class CreateBooks < ActiveRecord::Migration[7.0]
  def change
    create_table :books do |t|
      t.string :title
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
  end
end
class Book < ApplicationRecord
  belongs_to :user
  belongs_to :author
  belongs_to :shelf
end
class Api::BooksController < ApplicationController
  def index
    books = Book.all
    render json: book
  end
  
  def show
    book = Book.find(params[:id])
    render json: book
  end
  
  def create
    book = Book.new(book_params)
  
    if book.save
      render json: book, status: :created
    else
      render json: { errors: book.errors.full_messages }, status: :unprocessable_entity
    end
  end
  
  def destroy
    book = Book.find(params[:id])
    if book.destroy
      render json: { message: 'Book was deleted successfully' }
    else
      render json: { error: 'Failed to delete the Book' }, status: :unprocessable_entity
    end
  end
  
  private
  
  def book_params
    params.require(:book).permit(:title)
  end
end

我希望看到我在数据库中创建的书籍的名称。这是我在 Rails 控制台中完成的方法:

book = Book.new(title: "Pearl of Great Price")  
ruby-on-rails ruby model controller rm
1个回答
0
投票

您应该解决几个错误:

  1. 在这里,在控制器操作中,您应该使用
    books
    局部变量,这似乎是一个拼写错误:
def index
  books = Book.all
  render json: books
end
  1. 在Rails控制台中,您应该将记录
    save
    写入数据库(
    new
    方法仅初始化内存中的记录):
Book.create(title: "Pearl of Great Price")  

您可能还需要传递

user
,因为您有
belongs_to :user
和数据库约束,所以它需要类似于:

Book.create(title: "Pearl of Great Price", user: User.last)  
© www.soinside.com 2019 - 2024. All rights reserved.