ruby-on-rails - rails : HasManyThroughAssociationNotFoundError

标签 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

最佳答案

你需要添加

has_many :entries

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

关于ruby-on-rails - rails : HasManyThroughAssociationNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/944126/

相关文章:

ruby-on-rails - 如何保护 Rails 应用程序免受 Firesheep 攻击?

ruby-on-rails - 我可以在 Rails 中使用 link_to 创建链接数组吗?

ruby - 有没有比使用自定义 case 语句更实用的方法来用 Ruby 编写这个?

ruby-on-rails - 如何在递归方法中使用预加载集合

ruby-on-rails - 将 Rails Form Helpers 与序列化的自定义类一起使用

ruby-on-rails - Paperclip 会自动清理文件名吗?

ruby-on-rails - 我如何使用 Prawn 将表格内容跨越两个页面?

ruby-on-rails - Ruby require::File 语法

sql - Time.now.beginning_of_year 不从年初开始

ruby-on-rails - 如何使用 Rails 4 + PostgreSQL 查询关联记录列表?