gmacgregor
2007-Jan-26 02:40 UTC
Preferred find method: :has_many, :belongs_to relationship
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? --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
Matt Jones
2007-Jan-26 03:26 UTC
Re: Preferred find method: :has_many, :belongs_to relationship
On 1/25/07, gmacgregor <gmacgregor-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> > 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? >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 Jones mdj.acme-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org President/Technical Director, Acme Art Company (acmeartco.org) --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---