【问题标题】:weird rails4.1 has_many_through association bug奇怪的 rails4.1 has_many_through 关联错误
【发布时间】:2015-07-03 10:15:37
【问题描述】:

我正在使用 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

角色_职责

# == 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

在模型中。

我检查了所有的拼写和语法,但不知道为什么会出现这个错误?

谁能帮我找出错误?

【问题讨论】:

  • 你是如何访问的?

标签: ruby-on-rails ruby-on-rails-4 associations has-many-through


【解决方案1】:

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

【讨论】:

  • 如果您觉得有帮助,请随时接受我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2015-01-11
相关资源
最近更新 更多