Rails:HasManyThroughAssociationNotFoundError

时间:2009-06-03 10:52:30

标签: ruby-on-rails ruby activerecord has-many-through

我遇到了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 个答案:

答案 0 :(得分:112)

您需要添加

has_many :entries

对于每个模型,因为:through选项只指定了第二个关联,它应该用来查找另一个。

答案 1 :(得分:1)

@Meekohi 这意味着您没有Entry模型。我自己刚刚收到错误消息,所以想指出它(由于信誉低,不能将其作为评论发布)。

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

简单地运行

rails g model Entry

答案 2 :(得分:0)

您需要添加

has_many :entries

对于每个模型,以及has_many以上:通过,像这样:

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/