Dem1
@Dem1
Ruby on Rails developer

Как, вывести в таблицу все контракты данного раздела со счетами, если нету счетов, то все равно вывести контракт в таблицу с пустым значениям счетов?

class Invoice < ActiveRecord::Base
  belongs_to :contract
end

class Contract < ActiveRecord::Base
  has_many :invoices
  belongs_to :department	
end

class Department < ActiveRecord::Base
  has_many :contracts
end
  • Вопрос задан
  • 130 просмотров
Решения вопроса 1
viktorvsk
@viktorvsk
Как-то так:
# app/models/department.rb
class Department < ActiveRecord::Base
  has_many :contracts
  has_many :invoices, through: :contracts
end

# app/controllers/departments_controller.rb
def index
  @departments = Department.includes(contracts: [:invoices]).all
end

# app/views/departments/index.html.haml
%table
  %tr
    %td Name
    %td Contracts
  = render @departments


# app/views/departments/_department.html.haml
 %tr
  %td= department.name
  %td
    = render department.contracts


# app/views/contracts/_contract.html.haml
= contract.name
- if contract.invoices.present?
  = render contract.invoices
- else
  No invoices on this contract.
%hr/


# app/views/invoices/_invoice.html.haml
= invoice.total_sum
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы