Help with Relationship between 3 Tables #Rail

0

I would like your help with this issue below

I have 3 Tables:

Product           Purshase       Supplier
supplier_id      product_id        name


class Purshase < ActiveRecord::Base
    belongs_to :product
end

class Product < ActiveRecord::Base
    has_many :supplier
    has_many :purshase
end

class Supplier< ActiveRecord::Base
    belongs_to :product
end

I would like to present this in my view: purchase.product.supplier.name

Can anyone help me? Thank you very much.

    
asked by anonymous 26.05.2017 / 20:27

1 answer

0

Let's take the simpler way: A supplier has several products and the product can have several sales.

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

Now let's play on the 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">]>

Then we have:

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" 
    
14.07.2017 / 16:58