# Counting records in an association

**URL:** <https://www.ruby-forum.com/t/counting-records-in-an-association/133181>\
**Category:** Rails\
**Created:** [March 28, 2008, 4:03pm UTC](https://www.ruby-forum.com/t/counting-records-in-an-association/133181 "2008-03-28T16:03:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mridelmann](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f1d935/32.png) [@mridelmann](https://www.ruby-forum.com/u/mridelmann)\
**Post date:** [March 28, 2008, 4:03pm UTC](https://www.ruby-forum.com/t/counting-records-in-an-association/133181/1 "2008-03-28T16:03:53Z")

</div>

Hi,  
I would like to know how to count records in an association.  
My Models look like this:

// Users  
class User \< ActiveRecord::Base  
has\_many :read  
has\_many :books, :through =\> :read  
end

//Read  
class Read \< ActiveRecord::Base  
belongs\_to :user  
belongs\_to :book  
end

//Books  
class Book \< ActiveRecord::Base  
has\_many :read  
has\_many :books, :through =\> :read  
end

In my book\_controller I have these queries:  
@user = User.find(params[:user\_id])  
@topics = Topic.find(:all)  
@read\_by\_topic = Book.find(:all, :conditions =\>  
“topic\_id=#{@user.topic\_id.to\_i}”)  
@pending\_books = @read\_by\_topic - @user.books

If I use this code @user.assignments.count it returns the number of  
books I’ve read from the join model.

My question is, how do I find out how many of books I still need to  
read?  
@read\_by\_topic - @user.books returns an array but I can’t add a count.  
If I do it says I get an error that says, can’t convert Fixnum into  
Array.

Any help?

---

<div class="post-metadata">

**Author:** ![mridelmann](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f1d935/32.png) [@mridelmann](https://www.ruby-forum.com/u/mridelmann)\
**Post date:** [March 28, 2008, 10:38pm UTC](https://www.ruby-forum.com/t/counting-records-in-an-association/133181/2 "2008-03-28T22:38:32Z")

</div>

What does the assignments model look like?

---

<div class="post-metadata">

**Author:** ![mridelmann](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f1d935/32.png) [@mridelmann](https://www.ruby-forum.com/u/mridelmann)\
**Post date:** [March 29, 2008, 1:16am UTC](https://www.ruby-forum.com/t/counting-records-in-an-association/133181/3 "2008-03-29T01:16:52Z")

</div>

Not sure what you mean by “@read\_by\_topic - @user.books returns an array  
but I can’t add a count.”

Can you do @pending\_books.length maybe?
