Vamos seguir pelo caminho mais simples: Um fornecedor (supplier) tem vários produtos (products) e o produto pode ter várias vendas (purchase).
rails g model Supplier name:string
rails g model Product name:string supplier:references
rails g model Purchase name:string product:references
class Supplier < ActiveRecord::Base
has_many :products
has_many :purchases, through: :products
end
class Product < ActiveRecord::Base
belongs_to :supplier
has_many :purchases
end
class Purchase < ActiveRecord::Base
belongs_to :product
end
Agora vamos brincar no console:
> sup = Supplier.create name: "Fornecedor 1"
=> #<Supplier id: 1, name: "Fornecedor 1", created_at: "2017-07-14 14:54:02", updated_at: "2017-07-14 14:54:02">
> sup.products << Product.create(name: "Produto 1")
=> #<ActiveRecord::Associations::CollectionProxy [#<Product id: 1, name: "Produto 1", supplier_id: 1, created_at: "2017-07-14 14:54:45", updated_at: "2017-07-14 14:54:45">]>
> sup.products.first.purchases << Purchase.create(name: "Compra 1")
=> #<ActiveRecord::Associations::CollectionProxy [#<Purchase id: 1, name: "Compra 1", product_id: 1, created_at: "2017-07-14 14:55:36", updated_at: "2017-07-14 14:55:36">]>
Então temos:
Purchase.first
=> #<Purchase id: 1, name: "Compra 1", product_id: 1, created_at: "2017-07-14 14:57:11", updated_at: "2017-07-14 14:57:11">
> Purchase.first.product
=> #<Product id: 1, name: "Produto 1", supplier_id: 1, created_at: "2017-07-14 14:57:07", updated_at: "2017-07-14 14:57:07">
> Purchase.first.product.supplier
=> #<Supplier id: 1, name: "Fornecedor 1", created_at: "2017-07-14 14:57:03", updated_at: "2017-07-14 14:57:03">
> Purchase.first.product.supplier.name
=> "Fornecedor 1"
has_one :supplier
e nãohas_many :supplier
. Qual é situação correta do negócio, isto é, o produto pode ter vários fornecedores ou apenas um?