我需要的-是从4个表中获取数据。我需要有用户国家(地区),main_services名称,只有exportable: true
以及连接到main_service的每个最后一个Reservation_line中的数量。
这些是我模型的连接和表字段:
Reservatoin.rb:
# == Schema Information
#
# Table name: reservations
#
# id :integer not null, primary key
# from_date :date
# to_date :date
# ...
#
class Reservation < ApplicationRecord
belongs_to :user
has_many :reservation_lines, dependent: :destroy
end
User.rb:
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# ...
# country :string(255)
class User < ApplicationRecord
has_many :reservations, dependent: :destroy
end
ReservationLine.rb:
# == Schema Information
#
# Table name: reservation_lines
#
# id :integer not null, primary key
# reservation_id :integer
# quantity :integer
# serviceable_type :string(255)
# serviceable_id :integer
#
class ReservationLine < ApplicationRecord
belongs_to :reservation
belongs_to :serviceable, polymorphic: true, optional: true
end
MainService.rb:
# == Schema Information
#
# Table name: main_services
#
# id :integer not null, primary key
# name :string(255)
# main_service :boolean default(FALSE)
# input_type :string(255)
# exportable :boolean default(FALSE)
#
class MainService < ApplicationRecord
has_many :reservation_lines, as: :serviceable
end
因此,我决定编写一个作用域。看起来像这样:
预订模式:
scope :nationalities_with_date_test, -> (from, to) { joins(:user)
.joins(:reservation_lines)
.joins('INNER JOIN main_services ON main_services.id = reservation_lines.serviceable_id')
.where('reservation_lines.serviceable_type =?', 'MainService')
.where('main_services.exportable =?', true)
.select('users.country, main_services.name, SUM(reservation_lines.quantity) as quantity')
.where('reservations.from_date <= ? AND reservations.to_date >= ? AND (reservations.aasm_state = ? OR reservations.aasm_state = ? OR reservations.aasm_state = ?)',
to,
from,
'in_place', 'closed', 'finished')
.group('users.country')
}
如您所见,我将reservation_lines
表中的所有数量都拿走了,但是我只需要为每个main_service
都拿走最后一个,而我不知道该怎么办甚至根本没有可能。任何帮助,将不胜感激。谢谢。