簡體   English   中英

Ruby - 如何從 Rails 命令加入 output?

[英]Ruby - how to join output from a Rails command?

我希望能夠在我的數據庫上執行多項計算,所有計算都以用戶 ID 為中心,但我不知道之后如何重新組合它們。

假設我有三個表UserPurchasesDiscountUsage 我想找到用戶購買的最后日期和使用的折扣總數。 我會運行兩個單獨的命令:

User.joins(:purchases).group("users.id").select("users.id", "MAX(purchases.purchase_date)")
User.joins(:discount_usages).group("users.id").select("users.id", "COUNT(*)")

我希望我的最終 output 成為一張表,加入users.id ,但是來自select不是使用 Rails 函數的正確數據類型。 我如何表示來自兩個調用的users.id值是相同的,從而根據這些列加入它們?

您可以從連接表中聚合 select 並使用別名在 model 中訪問它們:

@users = User.joins(:purchases, :discount_usages)
            .select(
              "users.id", 
              "MAX(purchases.purchase_date) AS latest_purchase",
              "COUNT(discount_usages.*) AS discount_usages_count"
            )
            .group("users.id")

如果您想水合記錄 select users.*的其他屬性,而不僅僅是users.id

<table>
  <thead>
    <tr>
      <th>Id</th>
      <th>Latest Purchase</th>
      <th>Discount usages</th>
    </tr>
  </thead>
  <tbody>
    <% @users.each do |user| %>
    <tr>
      <td><%= user.id %></td>
      <td><%= user.latest_purchase %></td>
      <td><%= user.discount_usages_count %></td>   
    </tr>
    <% end %>
  </tbody>
</table>

我希望我的最終 output 成為一張表,加入 users.id,但是來自 select 的 output 不是使用 Rails 函數的正確數據類型。

不太清楚你在這里的意思。 此示例將像普通查詢一樣返回用戶記錄的集合。 如果您想要僅包含 arrays 數組的“原始”結果,請使用.pluck而不是.select

我假設用戶可能沒有任何購買,並且並非所有購買都使用折扣代碼。

但是,您需要每個用戶的完整列表,包括他們的最后購買日期和所有購買的總折扣使用情況。 您可能需要使用右連接。

就像是:

query = User.select('users.id AS user_id', 'MAX(purchases.purchase_date) AS last_purchase_date', 'COUNT(discount_usages.id) AS total_discount_usages')
  .joins('LEFT JOIN purchases ON purchases.user_id = users.id')
  .joins('LEFT JOIN discount_usages ON discount_usages.user_id = purchases.user_id')
  .group('users.id')
  .to_sql

然后為了獲取您可以使用的字段:

rows = ApplicationRecord.connection.select_all(query).to_hash

https://guides.rubyonrails.org/active_record_querying.html#select-all

這將為您提供一個帶有鍵的哈希數組:“user_id”、“last_purchase_date”、“total_discount_usages”。

...
<% rows.each do |row| %>
  <% row.symbolize_keys! %>
  <tr>
    <td><%= row[:user_id] %></td>
    <td><%= row[:last_purchase_date] %></td>
    <td><%= row[:total_discount_usages] %></td>
  <tr>
...

暫無
暫無

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

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