簡體   English   中英

如何在Ruby on Rails 2.3.14中從某個類的對象數組中選擇某個字段

[英]How do I select a certain field from an array of objects of a certain class in Ruby on Rails 2.3.14

如果我有一個名為Stream的類的100個對象組成的數組,如下所示:

User.find(1001).streams.find( :all, :order => "id", :limit => 100 )

這基本上是一個數據表,我如何從中選擇某個字段,例如等級? 在SQL中,我需要做的是, SELECT rating FROM streams WHERE user_id=1001 ORDER BY id LIMIT 100 ,但是我不知道如何在Ruby on Rails中做到這一點。 使用上面的命令返回所有字段,我無法使用。

以下代碼將返回一組rating

User.find(1001).streams.all( :order => "id", :limit => 100).map(&:rating) 

如果要避免檢索User對象的所有屬性的開銷:

User.find(1001).streams.all:select => "rating", 
  :order => "id", :limit => 100).map(&:rating) 

您可以在鍵:select的值中使用標准的SELECT子句語法。

如果要避免構造User對象:

User.connection.select_values("select rating from users order by id limit 100")

暫無
暫無

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

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