vanderleipinto / TT1

0 stars 0 forks source link

TT1 5 ActiveRecord sintaxe query #9

Closed vanderleipinto closed 7 months ago

vanderleipinto commented 7 months ago

Usando as tabelas do banco de dados do exercício anterior, escreva as classes das models Employee, Team e JobTitle, declare as associações das models e escreva a mesma query com a sintaxe do ActiveRecord.

Query

Nome completo, cpf, equipe e cargo dos colaboradores ordenando os por cpf.

Tabelas **Tabela employees** | first_name | last_name | cpf | team_id | job_title_id | |--------|--------|--------|--------|--------| | Pedro | Alves | 665.415.876-80 | 2 | 3 | Cell | | Tiago | Nogueira | 032.336.130-75 | 1 | 1 | Cell | | João | Neves | 461.636.517-23 | 1 | 2 | Cell | **Tabela teams** | id | name | |--------|--------| | 1 | Ti | | 2 | Suporte | | 3 | Financeiro | **Tabela job_titles** | id | name | |--------|--------| | 1 | Desenvolvedor back-endimpr | | 2 | Desenvolvedor front-end | | 3 | Encantador de clientes|
vanderleipinto commented 7 months ago

Classes das models:

Employee

class Employee < ApplicationRecord
  belongs_to :team
  belongs_to :job_title
end

Team

class Team < ApplicationRecord
  has_many :employees
end

JobTitle

class JobTitle < ApplicationRecord
  has_many :employees
end

Query em ActiveRecord

Query em SQL

Nome completo, cpf, equipe e cargo dos colaboradores ordenando os por cpf. ``` SELECT CONCAT(employees.first_name,' ', employees.last_name) AS full_name, cpf, teams.name AS equipe, job_titles.name AS cargo FROM employees JOIN teams ON employees.team_id = teams.id JOIN job_titles ON employees.job_title_id = job_titles.id ORDER BY CPF; ```

Query no ActiveRecord

employee = Employee.joins(:team, :job_title)
                   .select("CONCAT(employees.first_name, ' ', employees.last_name) AS full_name, employees.cpf, teams.name AS equipe, job_titles.name AS cargo")
                   .order(:cpf)

employee.each do |employee|
  puts "Nome completo: #{employee.full_name}, CPF: #{employee.cpf}, Equipe: #{employee.equipe}, Cargo: #{employee.cargo}"
end