简体   繁体   中英

Performance difference when calling class methods in model vs controller in rails?

In my rails app I am fetching a batch of data from the DB with around a million records. I am simply calling the following query combined with some pagination logic, and right now it is working very well. The code is defined in my model, like so:

def find_records(current_page, max_records, start_value, end_value)
   where(value_range: start_value..end_value)
        .offset((current_page - 1) * max_records).limit(max_records)
end

However, in my previous attempt, I had the following code defined in my model:

def find_records(max_records, start_value, end_value)
   where(value_range: start_value..end_value)
end

And I called .offset and .limit inside the controller like so:

def index
  current_page = params[:page]
  max_records = 3
  start_value = 4
  end_value = 8
  Model.find_records(start_value, end_value).offset((current_page - 1) * max_records).limit(max_records)
end

When I did this, my memory completely gave up on the 3rd or 4th page and my app just crashed. I don't know why calling .limit and .offset in the model solved the issue.

So my question is, how does calling class methods in your model rather than the controller improve code execution performance? I mean this query is obviously data-related so it makes sense to call it inside the model anyways, but I would still like to know the wonders behind the magic.

Thank you!

how does calling class methods in your model rather than the controller improve code execution performance?

It should not. Both your queries return a ActiveRecord::Relation . Both offset and limit are used to build the query, so in both scenarios you should see the same query in your logs. Please check your development.log when in doubt.

Having the code query code in your model makes sense. The controller shouldn't know all those details.

About the pagination, there are a few solutions in the rails world - Kaminari , will_paginate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM