Build versus new

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.

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

On Jul 3, 6:04 pm, “AnnaLissa C.” [email protected] 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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs