matsko
matsko

Reputation: 22193

Rails lazyload attributes when needed

I have a rails model that has a series of attributes (columns) that I do not want to have loaded for each select request. So what I would need to have done is to have it so that if an attribute is attempted to be accessed (via getter method) then it will do a select statement to fetch ALL of the columns from the database.

My question is that when I fetch the columns from the database, then is there a way that I can apply these attribute values with an activerecord value without me having to make a for loop to apply each attribute value?

Upvotes: 1

Views: 1255

Answers (2)

Tim Jasko
Tim Jasko

Reputation: 1542

https://github.com/jorgemanrubia/lazy_columns provides very similar functionality in convenient gem form. It lets you specify certain columns to be loaded lazily.

Upvotes: 0

moritz
moritz

Reputation: 25757

Try it this way:

def Person < ActiveRecord::Base
  def method_missing(method_id, *args, &block)
    begin
      super
    rescue
      reload
      super
    end
  end
end

And then initially load records like this (for example):

person = Person.select(:id).find(20)

And when you do

person.name

then it should hit method_missing and reload the record (with all attributes) when it fails.

Upvotes: 4

Related Questions