44

I have problems with getting a has_many through association to work.

I keep getting this exception:

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

These are the models involved:

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

And this is my 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
James Chevalier
  • 10,604
  • 5
  • 48
  • 74

3 Answers3

117

You need to add

has_many :entries

To each of your models, since the :through option just specifies a second association which it should use to find the other side.

Jon Wood
  • 2,589
  • 1
  • 20
  • 17
  • 2
    you can also use **t.references :warehouse, :null => false** instead of **t.integer "warehouse_id"** in the create table relationship... more Rail-lish nowadays. – carlosayam Aug 12 '12 at 03:02
  • 1
    With this change I get `NameError: uninitialized constant Article::Entry`? – Meekohi Nov 18 '14 at 04:33
7

You would need to add

has_many :entries

To each model, and above has_many :through, like this:

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

More detailed tutorial on how to handle view and controllers https://kolosek.com/rails-join-table/

Nesha Zoric
  • 6,218
  • 42
  • 34
2

@Meekohi This means that you have no Entry model. I just received the error message myself, so wanted to point it out (can't post it as a comment due to low reputation).

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

Simply run

rails g model Entry
mohnstrudel
  • 639
  • 8
  • 22