简体   繁体   中英

Rails / ActiveRecord controller boilerplate (call to .all)

I have the following boilerplate in a Cars controller

class CarsController < ApplicationController

# GET /cars
# GET /cars.json
def index
  @cars = Car.all

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @cars }
  end
end

Let's say I have 50,000 cars in my database.

My understanding is that each call to /cars/index will query the db ( select * from cars ), and build an object to store all that info. Then the Cars view would have access to @cars , and a json request would simply get a giant json response including all 50k cars.

  1. This default behavior sounds like a horrible idea in my situation. What if /cars is a very popular page? What if I had 10 million cars?
  2. I don't use @cars in the view ( index.html.erb ), so how can I verify that I don't need any json calls? (Does Rails need this for some reason I'm unaware of?)

It seems that @cars = Car.all is a very uncool line of code only used to validate that your new controller is working, and should probably be removed right in the beginning. Right?

Usually you should not want to display all "Cars" on a single page. Some filtering should occur before displaying the results. The most widespread solution would be to "paginate" the results for large datasets. Depending on implementation this should happen before the actual object is fetched from the database.

have a look at

https://github.com/mislav/will_paginate/wiki

Instead of all, you should use @car = Car.scoped . It will return an active record relation which will lazy-load car objects only when they are needed. Highly memory efficient.

For example, if you need only thirty cars from the @cars variable which is supposed to have all cars in database, @cars.limit(30) will load only those many.

On the other hand, if you used @cars = Car.all and then try @cars[0..29] , all cars get loaded into @cars anyway which will bloat the memory.

Excuse my english. I am finding it hard to type straight at the moment.

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