Rails: HasManyThroughAssociationNotFoundError - PullRequest
40 голосов
/ 03 июня 2009

У меня проблемы с получением has_many through ассоциации на работу.

Я продолжаю получать это исключение:

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

Это модели:

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

А это моя схема:

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

Ответы [ 3 ]

112 голосов
/ 03 июня 2009

Вам нужно добавить

has_many :entries

Для каждой из ваших моделей, поскольку опция: through просто указывает вторую связь, которую она должна использовать для поиска другой стороны.

1 голос
/ 11 августа 2015

@ Meekohi Это означает, что у вас нет модели Entry. Я только что получил сообщение об ошибке, поэтому хотел указать его (не могу опубликовать его как комментарий из-за низкой репутации).

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

Просто запустите

rails g model Entry
0 голосов
/ 03 сентября 2017

Вам нужно добавить

has_many :entries

Для каждой модели и выше has_many: through, например:

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

Более подробное руководство по работе с представлениями и контроллерами https://kolosek.com/rails-join-table/

...