簡體   English   中英

Rails:如何從列中獲取唯一值

[英]Rails: how can I get unique values from column

如何從表中的列中獲取唯一值? 例如,我有這個 Products 表:

ID NAME CATEGORY
1 name1 1st_cat
2 name2 2nd_cat
3 name3 1st_cat

在這里,我只想獲得 2 個值 - 1st_cat 和 2nd_cat:

<%Products.each do |p|%>
<%=p.category%>
<%end%>

還有兩種方式:

Product.select(:category).map(&:category).uniq # Ruby does the work

Product.uniq.pluck(:category) # DB does the work (superior)

對於Rails >= 5.1使用:

Product.distinct.pluck(:category) # DB does the work (superior)

...因為Relation#uniq棄用

我認為你可以這樣做:

<% Products.select("DISTINCT(CATEGORY)").each do |p| %>
<%= p.category %>
<% end %>

來源: http : //guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

這完成了數據庫服務器中的所有工作。 結果是一個簡單的數組。

<% Product.distinct(:category).pluck(:category).each do |category|
    <%= category %>
<% end %>

Rails 將生成適用於任何數據庫(Postgres、MySQL 等)的 SQL。

SELECT DISTINCT "products"."category" FROM "products"

我建議使用Products.all.distinct.pluck(:category)因為uniq自 rails 5 以來已被棄用,它將在 rails 5.1 上刪除

試試這個(在 rails 控制台中)

Product.group(:category)

Product.group(:category).each { |p| p.name }

對於 postgres

<% Product.select("DISTINCT ON (category) *").each do |category|
    <%= category %>
    <%= name %>
<% end %>

更新

甚至更好

<% Product.select(%(DISTINCT ON (category) "#{Product.table_name}".*)).each do |category|
    <%= category %>
    <%= name %>
<% end %>

因為它可以在您進行joins時返回錯誤的列(例如從連接表中返回id列,而不是products

需要獲得唯一的輸出並且嘗試使用“uniq”方法失敗。 嘗試了此處發布的幾種解決方案均未成功。 我正在使用設計它讓我可以訪問current_user方法並使用兩個表,一個是連接(一個項目 has_many :things)。

這個解決方案最終對我有用:

@current_user.things.select(:item_fk).distinct.each do |thing|
 <%= thing.item.attribute %>
<% end %>

如果您或任何人想從一個表中獲取兩個或多個屬性,例如products ,基於屬性的獨特特征,只有這個解決方案才能幫助您使用Rails >= 5.1

distinct_products = Product.select("DISTINCT ON (category) *")

# it's an active record relation class.
> distinct_products.class
=> Product::ActiveRecord_Relation

注意不要在distinct_products上使用.pluck() 它將從產品表中重新選擇,獨特的功能將不再起作用。

暫無
暫無

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

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