2009-06-03 9 views
37

Ho problemi con l'attivazione dell'associazione has_many through.Rails: HasManyThroughAssociationNotFoundError

Continuo a ricevere questa eccezione:

Article.find(1).warehouses.build 
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :entries in model Article 

Questi sono i modelli coinvolti:

class Article < ActiveRecord::Base 
    has_many :warehouses, :through => :entries 
end 

class Warehouse < ActiveRecord::Base 
    has_many :articles, :through => :entries 
end 

class Entry < ActiveRecord::Base 
    belongs_to :article 
    belongs_to :warehouse 
end 

E questo è il mio schema:

create_table "articles", :force => true do |t| 
    t.string "article_nr" 
    t.string "name" 
    t.integer "amount" 
    t.string "warehouse_nr" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "unit" 
end 

create_table "entries", :force => true do |t| 
    t.integer "warehouse_id" 
    t.integer "article_id" 
    t.integer "amount" 
end 

create_table "warehouses", :force => true do |t| 
    t.string "warehouse_nr" 
    t.string "name" 
    t.integer "utilization" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

risposta

108

È necessario aggiungere

has_many :entries 

A ciascuno dei vostri modelli, poiché l'opzione: through specifica solo una seconda associazione che dovrebbe utilizzare per trovare l'altro lato.

+2

puoi anche utilizzare ** t.references: warehouse,: null => false ** anziché ** t.integer "warehouse_id" ** nella relazione della tabella di creazione ... altro Rail-lish al giorno d'oggi. – carlosayam

+1

Con questa modifica ottengo 'NameError: costante non inizializzata Articolo :: Entry'? – Meekohi

1

@Meekohi Ciò significa che non si dispone di un modello Entry. Ho appena ricevuto il messaggio di errore personalmente, quindi volevo indicarlo (non posso postarlo come commento a causa della scarsa reputazione).

class Entry < ActiveRecord::Base 
    belongs_to :article 
    belongs_to :warehouse 
end 

semplicemente eseguire

rails g model Entry 
0

Si avrebbe bisogno di aggiungere

has_many :entries 

Per ogni modello, e soprattutto has_many: attraverso, come questo:

class Article < ActiveRecord::Base 
    has_many :entries 
    has_many :warehouses, :through => :entries 
end 

class Warehouse < ActiveRecord::Base 
    has_many :entries 
    has_many :articles, :through => :entries 
end 

più dettagliate tutorial su come gestire view e con trollers https://kolosek.com/rails-join-table/

Problemi correlati