2009-07-08 4 views
1

Je les modèles suivants:« NameError: constante uninitialized » lors de l'utilisation de nombreux à-plusieurs Rails

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 

Cependant, je reçois des questions lors de l'utilisation de cette relation. Account.first.account_holders fonctionne très bien, mais retourne 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' 

Toutes les idées?

Répondre

5

belongs_to requiert la forme singulière. En AccountHolder:

belongs_to :person 
1

J'ai eu le même problème et comme la réponse ci-dessus indique, il glissai quand j'ai changé la valeur de symbole belongs_to dans la table de jonction singulier (enlevé le « s » à la fin du nom).

Dans mon exercice, j'ai:

guy.rb

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

girl.rb

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

junction.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 

Ce nombre-to beaucoup de relations alors fonctionne ...

Questions connexes