belongs_to, has_many

Asked

Viewed 493 times

2

Hello everyone all good? I’m starting on Rails and got a little problem to make a simple web application with:

  • Customer registration (with name and address)
  • Employee register (only with name)
  • Work order register (with the date on which the O.S. was open, the client of this O.S., text with problem reported by customer, the employee who was activated to solve the problem of client and a boolean field to indicate if O.S. has been solved)

**All containing the CRUD

I created the Scaffolds

rails g scaffold Costumer name:string adress:string
rails g scaffold Employee name:string

Here comes the however. I created Scaffold so to make the relationship that exists:

rails g scaffold OrderService date:datetime description:text Costumer:reference Employee:references

I gave the rake db:create db:migrate to make everything happen in the bank

But then I don’t know what to do, if I use belongs_to, has_many...?

2 answers

1

In Active Record, associations function as connectors in memory of objects.

There are different types of associations: belongs_to, has_many, has_one, has_many :through, has_one :through and has_and_belongs_to_many. I’ll illustrate for you the two main.

has_many and belongs_to

When it comes to databases, has_many this indicates a one-to-many association (1:N). On the other hand, the belongs_to is a one-to-one relationship (1:1).

To illustrate, if a service order has an associated customer:

class ServiceOrder < ApplicationRecord
  belongs_to :customer
end

class Customer < ApplicationRecord
  has_many :service_orders
end

See that the other side of the association, Customer, indicates a relationship with the has_many. It is optional that you have has_many there, for he will only add the helper methods of the association. See:

service_order = ServiceOrder.first
service_order.customer
#=> retorna o cliente associado

and also

customer = Customer.first
customer.service_orders
#=> retorna todas as ordens de serviço do cliente

I recommend reading of Active Record Associations in the official Ruby on Rails guide.

1

  • Hello @Vitorc. Avoid putting links in your reply. You can put them as an add-on, but you should always try to post code that helps in solving the problem.

Browser other questions tagged

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