如何在Rails中添加所有记录而不使用`.each`?

huangapple go评论63阅读模式
英文:

rails How to add all the record without .each

问题

这段代码给我生成了许多图表。我想要一个包含所有用户的图表。我该怎么做?

<% User.all.each  do |e| %>
  <%= pie_chart e.products.group(:name).count %>
<% end  %>

我尝试了这个,但它不起作用,显示未定义方法 products

<%= pie_chart User.all.products.group(:name).count %>
英文:

This code gives me many chart. I want one chart for all the users. How can I do that

&lt;% User.all.each do |e| %&gt;
      &lt;%= pie_chart e.products.group(:name).count %&gt;
&lt;% end %&gt;

I tried this but it's not working undefined method `products'

&lt;%= pie_chart User.all.products.group(:name).count %&gt;

答案1

得分: 3

If you want to generate a single chart for all users without using the .each loop, you can modify your code as follows:

<%= pie_chart User.joins(:products).group('products.name').count %>

The User.joins(:products) part performs an inner join between the users and products tables, assuming there is an association between them. This ensures that only users with associated products are included in the query.

The .group('products.name') part groups the results by the name column of the products table.

Finally, the .count method counts the occurrences of each product name within the grouped results.

With this modified code, you should get a single chart displaying the count of each product name across all users.

英文:

If you want to generate a single chart for all users without using the .each loop, you can modify your code as follows:

&lt;%= pie_chart User.joins(:products).group(&#39;products.name&#39;).count %&gt;

The User.joins(:products) part performs an inner join between the users and products tables, assuming there is an association between them. This ensures that only users with associated products are included in the query.

The .group(&#39;products.name&#39;) part groups the results by the name column of the products table.

Finally, the .count method counts the occurrences of each product name within the grouped results.

With this modified code, you should get a single chart displaying the count of each product name across all users.

huangapple
  • 本文由 发表于 2023年6月8日 01:28:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定