grouping - Rails has_many association count child rows -


What is the "railroad" to calculate the number of children, and to capture all the ranks of the parents efficiently

I do not want to use counter_cache because I have these counts based on some time conditions.

Example of Clutch Blog: Articles table Each article has 0 or more comments.

I want to be able to draw how many comments in each article in the previous article, week, and week.

However, T wants to iterate on the list and do not want to make separate SQL calls for each article, and I do not want to use : Prefetch all data And process it on the app server.

I want to run a SQL statement and set one result with all information.

I know that I can work hard with full SQL, and maybe . Find and just : joins , : group , and : conditions parameters ... but I'm wondering if "Better" way ... aka "Rail Way"

Thanks in advance

This activation call should be what you want:

  Article.find (: all :, select = & gt; 'article. *, Count (posts.id)' postcount ', Left in the external post on positions: joins = & gt;., Carticle_ID = Article Es.id',: group => 'Articles.id')  

The script will return a list of objects, which method each post_count which involved a number of Post article as a string.

The method executes the SQL like the following:

  SELECT articles. *, Count (posts.id) as_c posts.article_id = articles.id GROUP by article.id  

If you are curious, then it is a sample of a query that you would like to query You can see by running:

  + ---- + ---------------- + ----------- - + | ID | Text | Postcount | + ---- + ---------------- + ------------ + | 1 | Text Text Text | 1 | | 2 | Text Text Text | 3 | | 3 | Text Text Text | 0 | + ---- + ---------------- + ------------ +  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -