2009-06-03 20 views
37

Tôi gặp sự cố khi nhận được liên kết has_many through để hoạt động.Đường ray: HasManyThroughAssociationNotFoundError

tôi tiếp tục nhận được ngoại lệ này:

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

Đây là những mô hình tham gia:

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 

Và đây là sơ đồ của tôi:

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 

Trả lời

108

Bạn cần phải thêm

has_many :entries 

Đối với mỗi mô hình của bạn, vì tùy chọn: through chỉ xác định liên kết thứ hai mà nó nên sử dụng để tìm mặt khác.

+2

bạn cũng có thể sử dụng ** t.references: warehouse,: null => false ** thay vì ** t.integer "warehouse_id" ** trong mối quan hệ tạo bảng ... thêm Rail-lish ngày nay. – carlosayam

+1

Với thay đổi này tôi nhận được 'NameError: uninitialized hằng số Article :: Entry'? – Meekohi

1

@Meekohi Điều này có nghĩa là bạn không có mô hình Entry. Tôi vừa nhận được thông báo lỗi chính mình, vì vậy muốn chỉ ra nó (không thể đăng nó như một bình luận do danh tiếng thấp).

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

Đơn giản chỉ cần chạy

rails g model Entry 
0

Bạn sẽ cần phải thêm

has_many :entries 

Để mỗi mô hình, và trên has_many: thông qua, như thế này:

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 

chi tiết hơn hướng dẫn về cách xử lý chế độ xem và con trollers https://kolosek.com/rails-join-table/