Topic: count not working properly

i am trying to count some items but it does not seem to be working properly

(rdb:1) x = Answer.select(:question_group_id).uniq
[#<Answer question_group_id: 4>, #<Answer question_group_id: 1>, #<Answer question_group_id: 7>]
(rdb:1) x.count
9

i see 3 items but it returns 9 can someone explain this

Thanks

Re: count not working properly

As explained in Rails API for select method:

Although in the above example it looks as though this method returns an array, it actually returns a relation object and can have other query methods appended to it, such as the other methods in ActiveRecord::QueryMethods.

It means that by calling 'count' you call it on Answer object; i.e.

Answer.count

which will return the total count of all Answer records. Try to use 'size' instead.

Last edited by Javix (2012-10-08 06:12:40)

Re: count not working properly

But what i am trying to count is unique

in this case i was expecting 3

[#<Answer question_group_id: 4>, #<Answer question_group_id: 1>, #<Answer question_group_id: 7>]

Re: count not working properly

Right, you are getting only unique values:

uniq(value = true)

Specifies whether the records should be unique or not. For example:

User.select(:name)
# => Might return two records with the same name

User.select(:name).uniq
# => Returns 1 record per unique name

User.select(:name).uniq.uniq(false)
# => You can also remove the uniqueness

But then what you are trying to do is to count them by calling 'count' method. An in this case the 'count' will be applied on Answer object (whole table).