执行rake db:migrate触发NameError: uninitialized constant Products错误求助
Ruby on Rails执行
rake db:migrate时遭遇NameError问题 我是Ruby on Rails(RoR)新手,正在搭建CRUD应用,执行rake db:migrate命令时终端反复报错:
NameError: uninitialized constant Products
mount Products::ProductsAPI => '/api/products'
我已经参考过相关建议,除Model文件product.rb(路径:\crud\app\models\product.rb)使用单数Product外,其他类和模块均命名为Products。完全复制教程代码,还执行了gem update --system更新gem(怀疑是Grape gem导致问题),但问题依旧。
我尝试过以下操作,均无效:
- 修改迁移文件名和类名使其匹配
- 调整路由文件中路由位置
- 核对并更新代码与教程完全一致
- 以管理员身份运行终端
- 在路由文件中替换为完整文件夹路径
- 更新gem并执行
bundle install
以下是相关文件代码:
Products Controller
class ProductsController < ApplicationController # GET method to get all products from database def index @products = Product.all end # GET method to get a product by id def show @product = Product.find(params[:id]) end # GET method for the new product form def new @product = Product.new end # POST method for processing form data def create @product = Product.new(product_params) if @product.save flash[:notice] = 'Product added!' redirect_to root_path else flash[:error] = 'Failed to edit product!' render :new end end # GET method for editing a product based on id def edit @product = Product.find(params[:id]) end # PUT method for updating in database a product based on id def update @product = Product.find(params[:id]) if @product.update_attributes(product_params) flash[:notice] = 'Product updated!' redirect_to root_path else flash[:error] = 'Failed to edit product!' render :edit end end # DELETE method for deleting a product from database based on id def destroy @product = Product.find(params[:id]) if @product.delete flash[:notice] = 'Product deleted!' redirect_to root_path else flash[:error] = 'Failed to delete this product!' render :destroy end end # we used strong parameters for the validation of params def product_params params.require(:product).permit(:name, :price, :old_price, :short_description, :full_description) end end
Product Model
class Product < ApplicationRecord validates :name, presence: true validates :price, presence: true, numericality: {:greater_than => 0} validates :short_description, presence: true end
数据库迁移文件
class CreateProducts < ActiveRecord::Migration[7.0] def change create_table :products do |t| t.string :name t.decimal :price t.text :short_description t.text :full_description t.timestamps end end end
路由文件
Rails.application.routes.draw do get 'products/index' get 'products/show' get 'products/new' get 'products/create' get 'products/edit' get 'products/update' get 'products/destroy' # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html resources :products root 'products#index' # Defines the root path route ("/") mount Products::ProductsAPI => '/api/products' # root "articles#index" end
内容的提问来源于stack exchange,提问作者Kerrr
相关产品推荐
相关产品推荐

