Group and count help?

Tables:

Blogs (id, name) Users (id, name) Pages (id, title, data) Visits (id, user_id, blog_id, page_id)

How many views every blog have? Result should be:: blog_id, blog_name, visits_count

How many times each page has been accessed? Result should be: page_id, page_title, page_data, visits_count

Tables:

Blogs (id, name) Users (id, name) Pages (id, title, data) Visits (id, user_id, blog_id, page_id)

How many views every blog have? Result should be:: blog_id, blog_name, visits_count

If you iterate through the blogs then for each blog visits_count = blog.visits.count and obviously the id and name are blog.id and blog.name. However if you find yourself using the id then you are probably not doing something the best way, it is unusual to have to reference the id directly.

How many times each page has been accessed? Result should be: page_id, page_title, page_data, visits_count

If you understand the answer above then I am sure you can work this one out.

The fact that you have asked this suggests that you are a beginner at rails, in which case I suggest you work right through a good tutorial such as railstutorial.org (which is free to use online). Then you should understand the basics of rails.

Colin

Colin Law wrote in post #1151111:

If you iterate through the blogs then for each blog visits_count = blog.visits.count

Thanks, its works!

But now I have added "liked" column to a visits-table:

Visits (id, user_id, blog_id, page_id, liked)

Default value is false but if user click "like"-link on a page its come to true.

But how can I count all likes?

page_likes_count = page.visits.liked.count Does not seem to work...

Think about it. page.visits is an activerecord association (effectively an array) of visits. You can call count on that which tells you how many in the array, but you can't call liked as that is a member of a single Visit object. You can call where() on an association however and then call count on that, so that is one way to do it. How are you getting on with the tutorial? It would answer all these basic questions for you so we do not need to use our time helping you when you could help yourself.

Colin

Colin Law wrote in post #1151137:

Ok. But is it possible to sort Pages by visits.count? I can't find it tutorial...

An sorting by likes is even more difficult?

You can sort by anything you like, in plain ruby if you can't see how to use order when fetching it from the database.

Colin

After two hours of trying I can't get sorting to work :frowning:

Well if you showed us your best try and tell us what did not work then we may be able to help.

But I would really much rather you first worked right through the tutorial I suggested, and also read and understand all the Rails Guides.

Colin