Matthew Denner
2005-Jul-23 10:47 UTC
"has_many :finder_sql" vs iterating over has_many relationship
Hi,
Wondering which is more efficient / RoR preferred:
class Foo < ActiveRecord::Base
has_many :bars
def active_bars
bars.inject([]) { |active,bar| active << bar if bar.active? }
end
end
Or:
class Foo < ActiveRecord::Base
has_many :bars
has_many :active_bars,
:class => ''Bar'',
:finder_sql => "select * from bars where f_id=#{id} and
active=1"
end
Hopefully I got the syntax on that second one right! Essentially, in
everyones opinion, is it better to iterate over an existing
''has_many''
relationship to find instances that are ''active'', or is it
better to
define another attribute where the result can be found from an SQL query?
I was writing the iteration technique, but then it occurred to me I
could achieve it with the finder_sql (incurring an extra DB query, but
not repeating the iteration on every call).
Matt
Michael Koziarski
2005-Jul-24 07:09 UTC
Re: "has_many :finder_sql" vs iterating over has_many relationship
On 7/23/05, Matthew Denner <matt-rdkfGonbjUS6Ep1eQ8kGe/TXAc8U3UkmXqFh9Ls21Oc@public.gmane.org> wrote:> Hi, > > Wondering which is more efficient / RoR preferred: > > class Foo < ActiveRecord::Base > has_many :bars > > def active_bars > bars.inject([]) { |active,bar| active << bar if bar.active? } > end > end > > Or: > > class Foo < ActiveRecord::Base > has_many :bars > has_many :active_bars, > :class => ''Bar'', > :finder_sql => "select * from bars where f_id=#{id} and > active=1" > endHow about both: class Foo < ActiveRecord::Base has_many :bars def active_bars bars.find(:all, :conditions=>"active=1") end end> Hopefully I got the syntax on that second one right! Essentially, in > everyones opinion, is it better to iterate over an existing ''has_many'' > relationship to find instances that are ''active'', or is it better to > define another attribute where the result can be found from an SQL query? > > I was writing the iteration technique, but then it occurred to me I > could achieve it with the finder_sql (incurring an extra DB query, but > not repeating the iteration on every call). > > Matt > _______________________________________________ > Rails mailing list > Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org > http://lists.rubyonrails.org/mailman/listinfo/rails >-- Cheers Koz