gpt4 book ai didi

ruby - irb 无权访问我的模型(NameError : uninitialized constant)

转载 作者:数据小太阳 更新时间:2023-10-29 08:02:47 26 4
gpt4 key购买 nike

我在 IRB 中尝试创建新的“Pin”时收到此错误。例如:

irb(main):001:0> @pin = Pin.first
NameError: uninitialized constant Pin

irb(main):001:0> @pin = Pin.new
NameError: uninitialized constant Pin

我必须改变一些东西,因为它以前是有效的。不幸的是,我找不到错误

这是我的引脚 Controller :

  class PinsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :set_pin, only: [:show, :edit, :update, :destroy]

def index
@pins = Pin.all
end

def show
@pin = Pin.find params[:id]
end

def new
@pin = Pin.new
end

def edit
end

def create
@pin = Pin.new(pin_params)
if @pin.save
redirect_to @pin, notice: 'Pin was successfully created.'
else
render action: 'new'
end
end

def update
if @pin.update(pin_params)
redirect_to @pin, notice: 'Pin was successfully updated.'
else
render action: 'edit'
end
end

def destroy
@pin.destroy
redirect_to pins_url
end

private

# Use callbacks to share common setup or constraints between actions.
def set_pin
@pin = Pin.find(params[:id])
end

def correct_user
@pin = current_user.pins.find(params[:id])
redirect_to pins_path, notice: "Not allowed!" if @pin.nil?
end

# Never trust parameters from the scary internet, only allow the white list through.
def pin_params
params.require(:pin).permit(:description)
end
end

这是我的联想,pin.rb

class Pin < ApplicationRecord
belongs_to :user
end

还有我对 User.rb 的联想:

class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

has_many :pins
end

和我的路线

Rails.application.routes.draw do
resources :pins
devise_for :users
root "pages#home"

get "about" => "pages#about"

end

最佳答案

irb 不会自动加载您的 Rails 环境,这就是为什么它无法访问您的模型(或助手、数据库或其他任何东西)的原因。但是,“rails 控制台”是一个 irb session ,它会加载所有 Rails 类、数据库连接等。

启动 Rails 控制台:

rails c

这是以下内容的简写:

rails console

这将为您的开发环境启动 Rails 控制台。你可以让它连接到你的测试环境:

rails c RAILS_ENV=test

或您的生产环境:

rails c RAILS_ENV=production

关于ruby - irb 无权访问我的模型(NameError : uninitialized constant),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40511503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com