belongs to, has many
Hello guys 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 registration (name only)
- Service Order Record (with the date 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 for indicate whether the O. S. has been resolved)
* * 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 though. I created the Scaffold like this 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 realize everything in the bank
But then I don't know what to do if I use belongs_to, has_many...?
2 answers
In Active Record, associations act as in-memory connectors for 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 will illustrate for you the two main ones.
has_many
and belongs_to
When talking about databases, has_many
indicates a one-to-many (1:N) Association. On the other hand, belongs_to
is a one-to-one (1:1) relationship.
To illustrate, if a service order has a customer associate:
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 to have has_many
there, because it 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 Active Record Associations in the official Ruby on Rails guide.
A tip since it is starting is whenever you go to do something Open rails guides and check if there is something else you need to do, it has practically everything there about rails
Https://guides.rubyonrails.org/association_basics.html#the-types-of-associations