1

我有以下型号:

class Person < ActiveRecord::Base
  has_many :accounts, :through => :account_holders 
  has_many :account_holders
end

class AccountHolder < ActiveRecord::Base
  belongs_to :account
  belongs_to :people
end

class Account < ActiveRecord::Base
  has_many :people, :through => :account_holders 
  has_many :account_holders
end

但是,我在使用这种关系时遇到了问题。Account.first.account_holders 工作得很好,但 Account.first.people 返回:

NameError: uninitialized constant Account::People
    from /Users/neil/workspace/xx/vendor/rails/activesupport/lib/active_support/dependencies.rb:105:in `const_missing'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/base.rb:2204:in `compute_type'
    from /Users/neil/workspace/xx/vendor/rails/activesupport/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/base.rb:2200:in `compute_type'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/reflection.rb:156:in `send'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/reflection.rb:156:in `klass'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/associations/has_many_through_association.rb:73:in `find_target'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/associations/association_collection.rb:353:in `load_target'
    from /Users/neil/workspace/xx/vendor/rails/activerecord/lib/active_record/associations/association_proxy.rb:139:in `inspect'

有任何想法吗?

4

2 回答 2

7

belongs_to 需要单数形式。在AccountHolder

belongs_to :person
于 2009-07-08T11:46:51.380 回答
1

我遇到了同样的问题,就像上面的答案所示,当我将联结表中的 belongs_to 符号值更改为单数(删除了名称末尾的“s”)时,它得到了修复。

在我的练习中,我有:

家伙.rb

class Guy < ActiveRecord::Base
  attr_accessible :name
  has_many :junctions
  has_many :girls, through: :junctions
end

女孩.rb

class Girl < ActiveRecord::Base
  attr_accessible :name
  has_many :junctions
  has_many :guys, through: :junctions 
end

连接点.rb

class Junction < ActiveRecord::Base
  attr_accessible :girl_id, :guy_id
  belongs_to :girl   # girls wouldn't work - needs to be singular
  belongs_to :guy    # guys wouldn't work - needs to be singular
end

然后这种多对多关系就起作用了……

于 2013-10-12T22:21:44.543 回答