开发者

Rails lazyload attributes when needed

开发者 https://www.devze.com 2023-03-18 06:59 出处:网络
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 att

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消