【问题标题】:NameError: uninitialized constant for has_many through relationshipNameError:has_many 的未初始化常量通过关系
【发布时间】:2012-11-06 21:13:07
【问题描述】:

我似乎无法做到这一点。我有很多通过关系只是不工作。这是设置:

class Group < ActiveRecord::Base
  belongs_to :user

  has_many :groups_phone_numbers, :dependent => :destroy
  has_many :phone_numbers, through: :groups_phone_numbers

  attr_accessible :name
end

class PhoneNumber < ActiveRecord::Base
  belongs_to :user
  has_many :responses

  has_many :groups_phone_numbers
  has_many :groups, through: :groups_phone_numbers

  attr_accessible :label, :number
end

class GroupPhoneNumber < ActiveRecord::Base

  belongs_to :group
  belongs_to :phone_number

end

我已经尝试了复数的所有变体,但无法克服未初始化的错误。我究竟做错了什么?数据库中的表(连接模型)称为 groups_phone_numbers。

确切的错误(g是一个组):

1.9.3p0 :002 > p g.phone_numbers
NameError: uninitialized constant Group::GroupsPhoneNumber

生成连接表的迁移:

class CreateGroupPhoneNumbersJoinTable < ActiveRecord::Migration
  def change
    create_table(:groups_phone_numbers) do |t|
      t.references :group
      t.references :phone_number

      t.timestamps
    end
  end
end

谢谢

【问题讨论】:

  • 你能添加确切的错误吗?
  • groups_phone_numbers 应该是group_phone_numbers,不是吗?
  • @MrYoshiji 我试过了……我试过每一个复数组合
  • 这些表的迁移是什么样的?
  • 只是为了确定,迁移正确执行了吗?表就这样存在于数据库中?

标签: ruby-on-rails activerecord has-many-through


【解决方案1】:

has_and_belongs_to_many 可能是您的最佳选择,只要您实际上不需要 GroupPhoneNumber。代码是这样的:

class Group < ActiveRecord::Base
  belongs_to :user

  has_and_belongs_to_many :phone_numbers

  attr_accessible :name
end

class PhoneNumber < ActiveRecord::Base
  belongs_to :user
  has_many :responses

  has_and_belongs_to_many :groups

  attr_accessible :label, :number
end

class CreateGroupsPhoneNumbersJoinTable < ActiveRecord::Migration
  def change
    create_table(:groups_phone_numbers, :id => false) do |t|
      t.integer :group_id
      t.integer :phone_number_id
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    相关资源
    最近更新 更多