Ruby on Rails - Count Entries on Scaffold

79 views Asked by At

In a simple Ruby on Rails applicaiton, I have a Scaffold called "Proposals" on which one of its columns is a string called "creationyear". I'm trying to count how many proposals have been created each year when the index page is loaded doing the following (in "proposals_controller.rb" file):

def index
  @proposals = Proposal.all
  @count2015 = Proposal.count(:all, :conditions => "creationyear = 2015")
  @count2016 = Proposal.count(:all, :conditions => "creationyear = 2016")
end

Somehow it is not working, since it gives me back on both variables the total number of entries on the scaffold.

Does anyone knows how to solve this one? I'm using Rails v4.2.6.

Thanks!

3

There are 3 answers

0
Eyeslandic On BEST ANSWER
@count2015 = Proposal.where(creationyear: '2015').count

If creationyear is a string, otherwise without the quotes.

0
Jayaprakash On

Why not you group the proposals by year?

@proposals = Proposal.group(:creationyear).count

or

@proposals = Proposal.group('creationyear').select('*, COUNT(*) as quantity')

This will reduce the queries happening for every year to one single query.

0
mikej On

The other answers here are fine, but it's worth providing a bit of background.

The way that count is used in Active Record has changed since earlier versions of Rails. It's possible you found an example from Rails 3 or earlier where conditions could be specified in the way you tried.

In more recent versions of Rails, count can be called with a column name e.g.

Person.count(:email) # number of person records that have an email address

but is used in other cases by creating the scope first, for instance by using where, and then calling count on that:

Proposal.where(creationyear: '2015').count