奇怪的 rails4.1 has_many_through 关联错误

weird rails4.1 has_many_through association bug

我正在使用 rails 4.1.12,最近尝试创建 has_many_through 关联。

我的榜样

# == Schema Information
#
# Table name: roles
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class Role < ActiveRecord::Base

  has_many :users
  
  has_many :roles_responsibilities
  has_many :responsibilities, through: :roles_responsibilities

end

责任模型

# == Schema Information
#
# Table name: responsibilities
#
#  id              :integer          not null, primary key
#  action_name     :string(255)
#  controller_name :string(255)
#  created_at      :datetime
#  updated_at      :datetime
#

class Responsibility < ActiveRecord::Base
  
  has_many :roles_responsibilities
  has_many :roles, through: :roles_responsibilities

end

Roles_responsibilities

# == Schema Information
#
# Table name: roles_responsibilities
#
#  id                :integer          not null, primary key
#  role_id           :integer
#  responsibility_id :integer
#  user_id           :integer
#  user_type         :string(255)
#  created_at        :datetime
#  updated_at        :datetime
#

class RolesResponsibility < ActiveRecord::Base
belongs_to :role
belongs_to :responsibility
end

我相信我做对了但是得到了一个奇怪的

 NameError: undefined local variable or method `  ' for Role (call 'Role.connection' to establish a connection):Class

模型中。

我检查了所有拼写和语法,但不确定为什么会出现此错误?

谁能帮我找出错误?

这是因为 ActiveRecord 对您的数据库连接进行了延迟加载。如果您再次 运行 查询,它应该可以正常工作,根据 this SO 问题。你可以通过 运行ning 之类的东西仔细检查 Role.count