Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8934025
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T09:41:26+00:00 2026-06-15T09:41:26+00:00

I do (in my view): # myUser is a User in ActiveRecord with :has_many

  • 0

I do (in my view):

# myUser is a User in ActiveRecord with :has_many :posts
myUser.posts.each do |post|
end

If the user had ten posts, would this be doing a database call ten times? Should these loops be like (less pretty)?:

myPosts = myUser.posts
myPosts.each do |post|
end

Here is a paste bin of a ruby file that I did to test. EDIT Modified the paste bin.

This reminds me of code in Java

for (int i = 0; i < someExpensiveFunction(); i++)

that should be (unless the array is modified)

for (int i = 0, len=someExpensiveFunction(); i < len; i++)

Am I missing something? I see a bunch of rails examples where people loop through some has_many field of an object. This is important to me as I’m trying to optimize my application’s performance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T09:41:26+00:00Added an answer on June 15, 2026 at 9:41 am

    If the user had 10 posts, this would technically be doing a database call 10 times?

    Nope.

    myUser = User.find 123
    myUser.posts.each do |post|
      puts post.title
    end
    

    This code here will run 2 queries. The first will find a user by its id, returning a single row. The second will run a query asking for all posts which have a user id that matches myUser. Then the each will use the result of that to iterate through.


    If you watch the log in development mode it tells you the queries it’s running, and you should see a single query returning all those posts.

    Rails uses an association proxy object to hold your query, execute the query when you need records, and then caches the result. It’s a very helpful bit of code and, for the most part, it handles things like this for you.

    This is a feature of Rails, not ruby.


    At the ruby level, each simply acts on collections.

    def get_letters
      puts 'executing "query"'
      sleep(3)
      ["a","b","c"]
    end
    
    get_letters.each do |item|
      puts item
    end
    

    This should print out.

    executing "query"
    a
    b
    c
    

    The get_letters method executes, it returns an array, an that array already full of data is what we call the each method on, so we can process each item. Fetching the collection and iterating through it are 2 completely separate steps.


    From your pastebin:

    # will this run forever?
    myArr = ["a","b","c"]
    myArr.each do |item|
      myArr.push("x")
    end
    

    Yeah it will, But not because the array is being “fetched” over an over.

    This equivalent to javascript like this, which spells it out better.

    myArr = ["a","b","c"];
    for (var i = 0; i < myArr.length; i++) {
      myArr.push('x');
    }
    

    The original array, on each iteration of the loop checks to see if it’s done yet. But because the array gets longer by one every single time we progress by one item, i < myArr.length will always be true because they both increase by one on each iteration. The same thing is going on in ruby with your each loop, for the same reason.

    It runs forever, not because you keep running some code to regenerate the array. It runs forever because you are artificially mutating the resulting array.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have users, posts and comments. User can post only one comment to each
For a specific database in a MySQL Server 5.5 I would like to view
View Looks Like This <?=form_open_multipart('upload/process');?> <input type=file multiple=multiple name=userfile[] id=userfile /> <?=form_submit('upload', 'Upload');?> <?=form_close();?>
In my User model I have: acts_as_authentic do |c| c.perishable_token_valid_for = 30.minutes end In
What would be the correct rails way to create a row in the Database
This is a is it possible question. I have one database file that contains
I have 2 methods like this in my user_helper.rb def full_name(user) if user.last_name? user.first_name
I have an entity relationship setup in my mvc2 application such that each user
I am doing two things with my user registration with Devise. Two step confirmation
I have a modal view that comes up requiring the user to verify his/her

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.