Lazy loading in Rails 3.2.6

前端 未结 3 1665
遥遥无期
遥遥无期 2021-02-07 07:13

I have found in several resources online than when doing stuff like:

cars = Car.where(:colour => \'black\')

The query is not executed, until

相关标签:
3条回答
  • 2021-02-07 07:42

    This is an interesting question....The answer is that when executing something in IRB/console, it calls inspect on the resulting object and then prints it out. If you did something like:

    User.where(:first_name => "John").class
    

    you should get back an ActiveRecord::Relation object.

    So the lazy loading for Rails still holds, it's just the way the console works.

    Hope this helps.

    Source(s): 1) https://rails.lighthouseapp.com/projects/8994/tickets/4951-rails-console-executes-where-queries-without-lazy-loading 2) Why Active Record relation is not returned in console?

    0 讨论(0)
  • 2021-02-07 07:42

    I ran a test using sqllite3 to attempt to find out if the AR Base find actually did a query immediately. Here is what I did:

    rows=Customer.orders.find(1,2)
    

    Then I did:

    ActiveRecord::Base.remove_connection;
    p rows
    

    I got a connection not established error.

    I also tried "p rows" immediately after the query w/o removing the connection and got the 2 rows I expected.

    This was done with activerecord-3.1.3. My conclusion is that in 3.1.3 base find waits to do the query until the array (Relation?) is accessed.

    I'm new at Ruby so my test might not be designed correctly.

    0 讨论(0)
  • 2021-02-07 08:00

    The console calls inspect on the result of any expression you type so that it can display it to you. inspect is one of the things that will trigger the load of the query. If you instead do

    x = User.where(:first_name => 'John'); false
    

    then you should see no query because this time the console is calling inspect on false instead of on the Active Record relation object.

    0 讨论(0)
提交回复
热议问题