NameError:未初始化不断通过关系的has_many [英] NameError: uninitialized constant for has_many through relationship

查看:200
本文介绍了NameError:未初始化不断通过关系的has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法得到这个权利。我有许多通过关系只是不能正常工作。这里的设置:

I can't seem to get this right. My has many through relationship just isn't working. Here's the setup:

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

我尝试了多元化的每一个变种,只是不能让过去的unintialized错误。我究竟做错了什么?在数据库中(合并模型)的表称为groups_phone_numbers。

I've tried every variant of pluralization and just can't get past the unintialized error. What am I doing wrong? The table in the database (join model) is called groups_phone_numbers.

确切错误(g为一组):

Exact error (g is a group):

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

迁移,使得连接表:

Migration that made the join table:

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

感谢

推荐答案

has_​​and_belongs_to_many可能是您最好的选择,只要你不需要GroupPhoneNumber实际。在code是这样的:

has_and_belongs_to_many could be the best choice for you, as long as you don't need GroupPhoneNumber actually. The code is like this:

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

这篇关于NameError:未初始化不断通过关系的has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆