Last active
August 15, 2018 23:24
-
-
Save LuisDeHaro/ebf92781b449aa1ee7b85f8f552dd672 to your computer and use it in GitHub Desktop.
ActiveModel::Serializers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Api::V1::DiscountScheduleSerializer < ActiveModel::Serializer | |
attributes :id, ... ,:created_at, :updated_at, :number_of_reservations | |
def created_at | |
object.created_at.in_time_zone.iso8601 if object.created_at | |
end | |
def updated_at | |
object.updated_at.in_time_zone.iso8601 if object.updated_at | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def some_action | |
@objects = DiscountSchedule.joins(:day_of_week) | |
.includes(:some_other_model_1, :some_other_model_2) | |
.joins("LEFT JOIN LATERAL ( | |
SELECT | |
COUNT(1) number_of_reservations | |
FROM reservations | |
WHERE ... some conditions ... | |
GROUP BY id | |
LIMIT 1 | |
) today_reservations_count ON true " | |
) | |
.where(is_active: true) | |
.select('number_of_reservations as number_of_reservations') | |
render( | |
json: ActiveModel::Serializer::CollectionSerializer.new( | |
@discount_schedules, | |
serializer: Api::V1::DiscountScheduleSerializer | |
), | |
status: :ok | |
) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
number_of_reservations as number_of_reservations, ... very big list of model fields ... | |
FROM "discount_schedules" | |
INNER JOIN "day_of_week" ON "day_of_week"."id" = "discount_schedules"."id_day_of_week" | |
LEFT OUTER JOIN "some_other_model_1" ... | |
LEFT OUTER JOIN "some_other_model_2" ... | |
LEFT JOIN LATERAL ( | |
SELECT | |
COUNT(1) number_of_reservations | |
FROM reservations | |
WHERE ... some conditions ... | |
GROUP BY id | |
LIMIT 1 | |
) today_reservations_count ON true | |
WHERE (discount_schedules.is_active = ('t')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment