Managing a lopsided has_and_belongs_to_many relationship

I’ve got a fixed list of several thousand Things, and a User base that
may grow to who knows how big (we can only hope ,right?) Users have and
belong to many Things. I want to display a list of top Things, based on
how many users each has. Things with 0 users are not displayed.

Two questions. First, I expect the density of the relatioships to focus
on a small percentage of the things. So while I may have 10,000 of
them, it might be true that only 100 have at least 1 user. In doing my
find statements, what would the syntax be to say “I am only interested
in Things where users.size > 0”? I’m hoping that I odn’t have to get
them all and simply choose not to display 90% of them, that seems like
unnecessary moving around of data.

Second, my goal is to sort these Things for presentation by users.size()
descending. Can I push my luck and get that out of the initial find
statement, or do I have to do my own sort?

Thanks!

Duane M. wrote:

I’ve got a fixed list of several thousand Things, and a User base that
may grow to who knows how big (we can only hope ,right?) Users have and
belong to many Things. I want to display a list of top Things, based on
how many users each has. Things with 0 users are not displayed.

Two questions. First, I expect the density of the relatioships to focus
on a small percentage of the things. So while I may have 10,000 of
them, it might be true that only 100 have at least 1 user. In doing my
find statements, what would the syntax be to say “I am only interested
in Things where users.size > 0”? I’m hoping that I odn’t have to get
them all and simply choose not to display 90% of them, that seems like
unnecessary moving around of data.

Second, my goal is to sort these Things for presentation by users.size()
descending. Can I push my luck and get that out of the initial find
statement, or do I have to do my own sort?

I’d recommend using a has_many :through if you’re doing stuff like that.
Here’s an old article I wrote on doing something similar (should be
updated RSN for 2.0) that should be enough to get you started…

http://blog.hasmanythrough.com/2006/6/12/when-associations-arent-enough-part-2

The counter_cache functionality has been beefed up some since then, and
you may find that useful too.

happy friday…


Josh S.
http://blog.hasmanythrough.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs