Good night people. I'm new to rails and I'm using translate to post in English.
a question. I have three tables: "ride_request_objects", "ata_objects" and "ride_requests".
They are related: Model: ride_requests
has_many :ride_request_objects
has_many :ata_objects, through: :ride_request_objects
Model: ride_request_objects
belongs_to :ata_object
Model: ata_objects
has_many :ride_request_objects
has_many :ride_requests, through: :ride_request_objects
I need to calculate the "total" in "ride_request_objects", which would be: ride_request_objects.quantity * ata_objects.unit_value
imagem da tabela: https://i.stack.imgur.com/uWv1g.png
How can I do this iteration for the calculation? would it be inside the Model of "ride_request_objects"?
CodePudding user response:
I'm assuming you want the total for each RideRequest
object (ie. not a single total for all records). If so then you can use a neat, almost hidden feature of ActiveRecord, where you can add arbitrary extra fields to a select and AR will automatically make them available as getters on the resulting objects, eg.
rrs = RideRequest.joins(:ata_objects).references(:ride_request_objects, :ata_objects).select( "ride_requests.*, SUM(ata_objects.unit_value * ride_request_objects.quantity) AS ata_sum").group(:id)
rrs.first.ata_sum