I have a "Has many through" relationship:
class Sale < ApplicationRecord
has_many :sales_status_histories
has_many :users, through: :sales_status_histories
has_many :status_sales, through: :sales_status_histories
end
class StatusSale < ApplicationRecord
has_many :sales_status_histories
has_many :users, through: :sales_status_histories
has_many :sales, through: :sales_status_histories
end
class User < ApplicationRecord
has_many :sales_status_histories
has_many :sales, through: :sales_status_histories
has_many :status_sales, through: :sales_status_histories
end
class SalesStatusHistory < ApplicationRecord
belongs_to :sale
belongs_to :status_sale
belongs_to :user
end
I want to select all the sales that has last specific status in the same query
I need to populate a panel with this informations
I'm doing this:
@status = StatusSale.where(id: [2,9,10])
@date = DateTime.current.beginning_of_month..DateTime.current.end_of_month
@sales_col_2 = Sale.distinct.joins(:sales_status_histories).where(sales_status_histories: {created_at: @date}).where(sales_status_histories: { status_sale_id: @status })
But this returns sales that had the status ids in any moment and not in the last