1:1 has_one

We can make 1:1 relationship to use has_one, belongs_to.

This is example

Create model Example

rails generate model employee last_name
rails generate model office location employee_id:integer

office has one employee, employee has office.

Database

Employee

last_name: string

Office

location: string
employee_id: integer

Association

employee.rb

class Employee < ActiveRecord::Base
   has_one :office
end
&#91;/ruby&#93;
office.rb
&#91;ruby&#93;
class Office < ActiveRecord::Base
   belongs_to :employee   # employee_id
end
&#91;/ruby&#93;
Add belongs_to to id holder.

<h3>Set</h3>
[ruby]
Employee.create(last_name:'Yuzuru')
Employee.create(last_name:'Yama')
Office.create(location:'2nd floor', employee_id:Employee.first.id)
Employee.first.office   # 2nd floor
Office.first.employee   # Yuzuru

Create, Destroy

Employee.last.create_office(location:'1st floor')
Employee.first.office.destroy

Use

@office = Office.find(1)
@employees = Employee.where(office_id:@office.id)
@employee = Employee.find(1)
@office = @employee.office