41 ruby activerecord ruby-on-rails has-many-through
我有一个has_many through
关联工作的问题.
我一直得到这个例外:
Article.find(1).warehouses.build
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :entries in model Article
Run Code Online (Sandbox Code Playgroud)
这些是涉及的模型:
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
Run Code Online (Sandbox Code Playgroud)
这是我的架构:
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
Run Code Online (Sandbox Code Playgroud)
Jon*_*ood 113
你需要添加
has_many :entries
Run Code Online (Sandbox Code Playgroud)
对于每个模型,由于:through选项只指定了第二个关联,它应该用于查找另一侧.
你需要添加
has_many :entries
Run Code Online (Sandbox Code Playgroud)
对于每个模型,以及上面的 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
Run Code Online (Sandbox Code Playgroud)
关于如何处理视图和控制器的更详细教程https://kolosek.com/rails-join-table/
归档时间: |
|
查看次数: |
13536 次 |
最近记录: |