Preferred find method: :has_many, :belongs_to relationship


#1

I’m looking for some clarification regarding finds in a :has_many,
:belongs_to relationship. Consider:

class User < ARB
has_many :tasks
end

class Task < ARB
belongs_to :user
end

Both of these methods in a controller yield the same result:

def find_tasks_for_user
@user = User.find(params[:id])
@tasks = Task.find_all_by_user_id(params[:id])
end

def find_tasks_for_user
@user = User.find(params[:id])
@tasks = @user.tasks
end

I’m assuming that the latter is the more idiomatic of the two. But is
there anything “wrong” with the first approach?


#2

On 1/25/07, gmacgregor removed_email_address@domain.invalid wrote:

end
@tasks = @user.tasks
end

I’m assuming that the latter is the more idiomatic of the two. But is
there anything “wrong” with the first approach?

No, but the second approach lends itself to being optimized using
:include - thusly:

def find_tasks_for_user
@user = User.find(params[:id], :include => :task)
@tasks = @user.tasks
end

Or the :include can be added to the model definition.

There may also be some advantages in that @user.tasks will cache the
value, so
that if code in the view asks for it again, it will avoid another trip
to the DB.


Matt J.
removed_email_address@domain.invalid
President/Technical Director, Acme Art Company (acmeartco.org)