我是 Ruby On Rails 开发的新手,我正在构建一个包含类用户、书籍、作者和书架的 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")
您应该解决几个错误:
books
局部变量,这似乎是一个拼写错误(books
vs book
):def index
books = Book.all
render json: books
end
new
方法仅初始化内存中的记录,请参阅docs):Book.create(title: "Pearl of Great Price")
或
book = Book.create(...)
book.save
您可能还需要传递
user
,因为您有 belongs_to :user
和数据库约束,所以它需要类似于:
Book.create(title: "Pearl of Great Price", user: User.last)