Rails:HasManyThroughAssociationNotFoundError

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 

你需要添加

 has_many :entries 

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

@Meekohi这意味着你没有Entry模型。 我刚刚收到错误消息,所以想指出(由于低信誉,不能发表评论)。

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

只需运行

 rails g model Entry 

你需要添加

 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/