Re: Method on a array of objects from the database

Pierre Valade
Thu, 29 Nov 2007 19:52:59 -0000

Thank you for your answer but my question is how to add method to an
array of @products.

I have : @products.find(:all)

Then, if I want to select only fruits from @products, I could do :
@products.select {...}
And it''s this select that I want to put in a method select_fruits so
that I could do :

@products.select_fruits which corresponds to @products.select { ... }

Thank you,
Pierre

On 29 nov, 20:48, Greg Willits
<li...-0Bv1hcaDFPRk211Z5VL+QA@public.gmane.org>
wrote:
> On Nov 29, 2007, at 11:23 AM, Pierre Valade wrote:
>
>
>
> > I would like to know the more elegant way to add a method for an array
> > of objects from the database.
>
> > Let me give an example :
>
> > Class Product
> >  ....
> > end
>
> > And in my controller :
>
> > @products = Product.find(:all)
>
> > And now I want to define a method which I could like
>
> > @products.select_fruits
>
> > having said somewhere :
>
> > def select_fruits
> >  ....
> > end
>
> Is you question about where those methods should go? They can, and
> usually should, go in the model.
>
> class Product
>
> def self.find_all
>    find(:all, .....)
> end
>
> def self.select_fruits(parameters)
>     find(:all, :conditions...
> end
>
> end
>
> --- controller --
>
> fruits = Product.select_fruits(:fruit_type = params[:....])
>
> --
> def gw
>    acts_as_n00b
>    writes_at(www.railsdev.ws)