Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the minimum value in a table column in Rails 3

Hi lets say I have a table(ads) with a column(views)

Views
2
1
4
6
3

How do I find the smallest value in this column? Any easy way to do this?


This is what I have
@ads = Ad.all
@show_this_ad = @ads.min(:views)

this gives me a "wrong number of arguments(1 for 0) error"


@ads = Ad.all
@show_this_ad = @ads.minimum(:views)

this gives me a "undefined method error"

like image 632
Francois Avatar asked Dec 13 '11 10:12

Francois


1 Answers

Ad.minimum(:views)

should work

You can still add more restrictions like:

Ad.where(:user_id => 12345).minimum(:views)

To find only adds by the user with id 12345

btw: You can easily test such things in the rails console (just type "rails c" from the commandline) One thing that often helps me is just to get the class of the result of some operation.

If you enter something like:

@foo = Add.all

And then:

@foo.class

You will see, that @foo is an array, which of course doesn't know anything of ActiveRecord#minimum

like image 145
thorsten müller Avatar answered Oct 18 '22 05:10

thorsten müller