Search code examples
ruby-on-railsrailstutorial.org

Does rails touch the database before building a form from form helper?


Working through the rails tutorial and it says

When constructing a form using form_for(@user), Rails uses POST if @user.new_record? is true and PATCH if it is false.

So when it renders the html is it hitting the database and when does it do that exactly? What comes right before?


Solution

  • Nope, it doesn't hit the database, you can check for yourself in the console,

    old = User.last
    new = User.new
    

    Only the old hits the database, whereas, new just creates the object of class User, let's go further..

    old.new_record?
    #=> false
    new.new_record?
    #=> true
    

    See, no query is hit to the database, similarly, when you pass the @user object to form, it checks for new_record? but without hitting the db.

    So, how does it determine this? My wild guess, it checks for id/primary_key not nil