# Build versus new

**URL:** <https://www.ruby-forum.com/t/build-versus-new/142138>\
**Category:** Rails\
**Created:** [July 3, 2008, 7:40pm UTC](https://www.ruby-forum.com/t/build-versus-new/142138 "2008-07-03T19:40:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![AnnaLissa\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ce73a5/32.png) [@AnnaLissa\_C](https://www.ruby-forum.com/u/AnnaLissa_C)\
**Post date:** [July 3, 2008, 7:40pm UTC](https://www.ruby-forum.com/t/build-versus-new/142138/1 "2008-07-03T19:40:17Z")

</div>

I like the simplicity and elegance of creating a new associated object  
with:

@todo = @current\_user.todos.build(params[:todo])

versus

@todo = Todo.new(params[:todo])  
@todo.user = @current\_user

But isn’t the first solution inherently slower since ‘todos’ makes a  
call to  
the database first and return all Todo objects for @current\_user?

Same with ‘find’ on a collection. That is, isn’t

@todo = @current\_user.todos.find(params[:id])

much slower than

@todo = Todo.find\_by\_id\_and\_user\_id(params[:id], @current\_user.id) ?

Thanks. I’m very interested in finding out why one method is preferred  
over  
the other.

---

<div class="post-metadata">

**Author:** ![AnnaLissa\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ce73a5/32.png) [@AnnaLissa\_C](https://www.ruby-forum.com/u/AnnaLissa_C)\
**Post date:** [July 3, 2008, 7:43pm UTC](https://www.ruby-forum.com/t/build-versus-new/142138/2 "2008-07-03T19:43:14Z")

</div>

AnnaLissa C. wrote:

> But isn’t the first solution inherently slower since ‘todos’ makes a
> 
> Thanks. I’m very interested in finding out why one method is preferred  
> over the other.

Look at your logs in development mode : @current\_user.todos doesn’t  
fetch all objects but creates a Proxy object which then may or may not  
fetch all objects based on which method you call on it.

Lionel

---

<div class="post-metadata">

**Author:** ![AnnaLissa\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ce73a5/32.png) [@AnnaLissa\_C](https://www.ruby-forum.com/u/AnnaLissa_C)\
**Post date:** [July 3, 2008, 7:42pm UTC](https://www.ruby-forum.com/t/build-versus-new/142138/3 "2008-07-03T19:42:38Z")

</div>

On Jul 3, 6:04 pm, “AnnaLissa C.” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> @todo = Todo.find\_by\_id\_and\_user\_id(params[:id], @current\_user.id) ?

Nope, because neither of those will load the todos collection.  
@current\_user.todos does not load all todos: it’s a proxy class. That  
class has a certain number of methods (eg build, find, etc…) for  
anything it can’t handle it will load the collection and call the  
method on the resulting array,

Fred
