簡體   English   中英

Rails分組方式

[英]Rails Way of Grouping By an Association

我知道我正在使這一過程變得更加困難。 必須有一種完成此任務的方法。 演示:這是兩個模型:

#app/models/user.rb
class User < ActiveRecord::Base
  has_many :blogs

  def to_s
    name
  end
end

#app/models/blog.rb
class Blog < ActiveRecord::Base
  belongs_to :user
    delegate :name, to: :user, prefix: true, allow_nil: true

  def to_s
    title
  end
end

所以我要做的是將所有blogs按相關user分組。 然后,我想列出每個user blogs

關鍵細節 :並非所有blogs都具有關聯user 有些具有user_id = nil 以下是要演示的博客列表(最后兩個博客的user_id = nil ):

列出博客

所以我得到了我想要的工作。 但是解決方案不容易閱讀,我知道必須有某種方法可以使用Rails的查詢接口來完成此任務。 我無法弄清楚,因此我在下面總結了自己的解決方案:

#app/controllers/admin_controller.rb
class AdminController < ApplicationController
  def index
    @group_blogs_by_user = {}
    User.all.pluck(:name).each{|user| @group_blogs_by_user[user] = []}
    @group_blogs_by_user[nil] = [] #provide nil category when no user_id was specified for a blog

    Blog.all.each {|blog| @group_blogs_by_user[blog.user_name].push(blog)}

    @group_blogs_by_user.reject!{ |_ , v|v.empty?} #do not show users that have no blogs
  end
end

這是顯示它的視圖:

#app/views/admin/index.html.erb
<h1>Showing Count of Blogs per User</h1>
<table>
  <thead>
    <th>User</th>
    <th>Blogs Count</th>
  </thead>
  <tbody>
        <% @group_blogs_by_user.each do |user, blogs_of_this_user| %>      
        <tr>
      <td><%= user || "No User Specified"%></td>
      <td><%= blogs_of_this_user.size %></td>
    </tr>
  <% end %>
  </tbody>
</table>

<hr>

<h1>Showing Breakdown of Blogs per User</h1>
<% @group_blogs_by_user.each do |user, blogs_of_this_user| %>
  <h3><%= (user || "No User Specified") + " (#{blogs_of_this_user.size} blogs)" %></h3>
  <table class="table">
    <thead>
        <th>Blog ID</th>
        <th>Created At</th>
    </thead>
    <tbody>
    <% blogs_of_this_user.each do |blog| %>
      <tr>
        <td> <%= link_to(blog.id, blog)%></td>
        <td> <%= blog.created_at.strftime("%d-%m-%Y")%></td>
      </tr>
    <% end %>
    </tbody>
  </table>
<% end %>

這就是它所呈現的,這就是我想要的:

按用戶分組的博客

我一直在遇到這種情況,我想通過某種關聯對表進行分組,但我發現自己一直在不斷尋找解決方案。 如何使用Rails的查詢界面實現Rails的方式?

要從用戶那里獲取所有博客並打印用戶名,blog_id和博客計數

<% @users.each do |user| %>
    <%= user.name %>
    <%= user.blogs.count %>
    <% user.blogs.each do |blog|%>
        <%= blog.id %>
    <% end %>
<% end %>

在沒有用戶的情況下獲取大量博客

<%= Blog.where(user: nil).count %>

希望我能正確回答您的問題,這對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM