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 开发者_StackOverflow中文版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?
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.
https://github.com/jorgemanrubia/lazy_columns provides very similar functionality in convenient gem form. It lets you specify certain columns to be loaded lazily.
精彩评论