Forum: Ruby on Rails Preferred find method: :has_many, :belongs_to relationship

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
gmacgregor (Guest)
on 2007-01-26 04:41
(Received via mailing list)
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?
Matt J. (Guest)
on 2007-01-26 05:26
(Received via mailing list)
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)
This topic is locked and can not be replied to.