【问题标题】:Rails NameError 'uninitialized constand User::Events' using deviseRails NameError 'uninitialized constand User::Events' 使用设计
【发布时间】:2020-10-28 06:44:39
【问题描述】:

我觉得标题可能更具体,但我很难理解这个问题,而且我不确定问题是什么,所以我很抱歉。

我有用户,用设计创建,用户可以制作活动,并且活动有很多用户作为参与者与他们关联。

我的用户模型:

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

  has_many :created_events, foreign_key: :owner_id, class_name: "Events"
  has_many :attendees, through: :attendees

end

我的事件模型

class Event < ApplicationRecord
  belongs_to :owner, class_name: 'User'
  has_many :attendees, through: :attendees
end

我的与会者模型,加入两者

class Attendee < ApplicationRecord
  belongs_to :attendee, class_name: "User"
  belongs_to :attended_event, class_name: "Event"
end

在我的 users_controller 文件中尝试使用类似的东西时,我收到“未初始化的常量 User::Events”错误,转到 /users/[:id]:

class UsersController < ApplicationController

  before_action :authenticate_user!

  def show
    @user = User.find(params[:id])
    @created_events = @user.created_events.all
  end

end

或在执行新操作时 > 在 events_controller 文件中创建操作:

def new
  @event = Event.new
end

def create
  @event = current_user.created_events.build(event_params)

    respond_to do |format|
      if @event.save
        format.html { redirect_to @event, notice: 'Event was successfully created.' }
        format.json { render :show, status: :created, location: @event }
      else
        format.html { render :new }
        format.json { render json: @event.errors, status: :unprocessable_entity }
    end
  end
end

在我添加连接模型之前它工作正常,现在我收到错误:

uninitialized constant User::Events

提前致谢。这个我真的很难受。

【问题讨论】:

    标签: ruby-on-rails events nameerror model-associations uninitialized-constant


    【解决方案1】:

    简单的错字:

    has_many :created_events, foreign_key: :owner_id, class_name: "Events"
    

    应该是class_name: 'Event'

    【讨论】:

    • 我喜欢编程...非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多