I have a common situation and would like best practice suggestions from some of you more experienced rails developers. In my DB I''ve normalized tables in a traditional manner, e.g. I have Posts which have authors stored in a Users table. My problem is when I go to show a list of Posts and I want to display the author name (e.g. post.author.name) ActiveRecord appears to do a SELECT on the Users table for each post. If I want to display additional author properties (e.g. phone_number), additional queries are generated. Clearly this is a performance penalty for my normalization. What''s the recommended way for avoiding the performance penalty WITHOUT de-normalizing? In C# or Java I''d cache the "static" User data and do in-memory lookups, but in Rails I''m not sure how I''d set up such a cache even if that were the right solution. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://wrath.rubyonrails.org/pipermail/rails/attachments/20060624/5288b2d6/attachment.html
You could try: Post.find(:all, :include => :author) This is on p244 of "Agile Web Development with Rails", which mentions that this will only work for databases which support LEFT OUTER JOIN. It is designed to avoid just the situation you are having by preloading the child rows. Julian -- Posted via http://www.ruby-forum.com/.
Scott R Brittain wrote:> I have a common situation and would like best practice suggestions > from some of you more experienced rails developers. > > In my DB I''ve normalized tables in a traditional manner, e.g. I have > Posts which have authors stored in a Users table. > > My problem is when I go to show a list of Posts and I want to display > the author name (e.g. post.author.name ) > ActiveRecord appears to do a SELECT on the Users table for each post > . If I want to display additional author properties > (e.g. phone_number ), additional queries are generated. Clearly this > is a performance penalty for my normalization. > > What''s the recommended way for avoiding the performance penalty > WITHOUT de-normalizing?My piggy back plugin seems to address this issue. See http://railsexpress.de/blog/articles/2006/05/29/simpler-piggy-backing. -- stefan -- Rails performance tuning: http://railsexpress.de/blog Subscription: http://railsexpress.de/blog/xml/rss20/feed.xml
On 6/24/06, Julian Gall <julian.gall@gmail.com> wrote:> You could try: > > Post.find(:all, :include => :author) > > This is on p244 of "Agile Web Development with Rails", which mentions > that this will only work for databases which support LEFT OUTER JOIN. It > is designed to avoid just the situation you are having by preloading the > child rows. > > JulianThis is called ''eager loading'' if you''d like to google for more information. Isak