Home > OS >  How to make a subtraction between 2 records from the same column using rails?
How to make a subtraction between 2 records from the same column using rails?

Time:08-29

Hi Stackoverflow team.

I'm using ruby on rails and i'm trying to find the code to make a subtraction between 2 records from the same column using rails.

I have the following table

customers
    id    num_hid     num_oxi
    1        1           2
    2        3           4
    3        5           6
    4        7           8

I'm trying to get this result

 @result =  last_num_hid_id_4 -  last_num_hid_id_3
 //calcultion is: 7-5 = 2

i did this code but this displays the last 2 records in array

<% @customers.each.last(2) do |customer|%> %>
  <%= customer.num_hid %>
<% end %>

i tried this code but is only showing the last record

@last_customer =Customer.all.last
@last.num_hid

Can somebody help me with this issue?

I will appreciate all your comments.

Thanks in advance.

CodePudding user response:

You can define class method in your model like this

class Customer < ActiveRecord::Base
  def self.subtraction(atr)
    last[atr] - second_to_last[atr]
  end
end

or more efficient

class Customer < ActiveRecord::Base
  def self.subtraction(atr)
    last(2).pluck(atr).reverse.inject(:-)
  end
end

And then call it after your model scope

For example

Customer.order(id: :desc).subtraction(:id)
# => -1 # if there is continuous sequence of ids
  • Related