Normally rails loads data with a :select => "*" from the开发者_StackOverflow社区 database. I know I could change this. But I'd like to go another way: always only select "id" and load the attributes automatically later on when they are needed.
Example: accessing user.description should if it's been loaded yet. if not, trigger a "SELECT description FROM users WHERE id=#{self.id}" and set it.
Anyone know if there's a rails plugin which does this? Or how to implement it?
Thanks, Corin
I wrote a Rails plugins that does exactly this lazy_columns. Notice that a much better approach is to create a new model with the big columns you want to load on demand (since Rails load related objects lazily by default).
A quick google search turned up this, but I'm with glongman. I can't imagine what kind of performance issue would require this...
It is wise to just refactor your main "huge blob" fields into a separate model (like BookBody) which is usually not needed when operating with models in bulk. Alternatively, you can use the :select
option on finders
BookWithHugeBlobOfText.find(:first, :select=>"only,small,columns")
Records selected that way will be readonly since the Rails philosophy says (and rightfully so!) that you need to have all data on the model to validate it. Lazy loading would be a nice to have, but as it stands now I would discourage you from using monkeypatch plugins for this.
Another option would be to create a SQL view which would only contain the lightweight fields and run your ops from there.
精彩评论