Order by the number of repeat entries in Rails
I'm building an app where users can submit开发者_如何学C a URL, and I want to find out how many of a specific URL have been submitted on the site in total, and then arrange them in a list ordered by the number of times they've been submitted.
Any ideas? Using Rails 3.0.6
If you're allowing duplicate urls, and assuming you have a Url
class with a url
column
Url.group(:url).select("urls.*,count(*) as num").order("num desc")
If you have unique urls and a join table between urls and users (which is what you should be doing):
Url.joins(:users).group("urls.id").select("urls.*, count(*) as num").order("num desc")
if i understand well, you want to keep track of all links submitted by the users via a form.
You could use a submitted_urls table with two columns: "url" (with an index and a unicity constraint) and "count" (with an index).
When submitting a new link, have your controller to check if the url exists in the table; if not, create it, else increment the counter associated to this url.
listing your links is now as simple as querying this table with an order('count DESC') clause, and counting the total number of links is just a matter of count().
if i did not understood well, this means you want to implement some kind of analytics dashboard for your site ; why not use google analytics then ?
精彩评论