Help With Relationship Between 3 #Rails Tables

Asked

Viewed 266 times

0

I would like your help in this problem 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’d like to present it on my view like this: Purchase.product.Supplier.name

Could someone help me ? Thank you very much.

  • To do something like this each product should have only one supplier, and so the relationship would have to be has_one :supplier and not has_many :supplier. What is the correct business situation, that is, the product may have multiple suppliers or only one?

1 answer

0

Let’s go the simple way: One supplier (Supplier) has several products (products) and the product can have multiple sales (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

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" 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.