簡體   English   中英

Rails模型范圍和組

[英]Rails model scope and group

我想獲得所有注冊階段為1、2、3、4、5或6的用戶,然后將它們分組為注冊階段。

class User < ActiveRecord::Base

    scope :incomplete_onboarding, -> { where(registration_stage: [1, 2, 3, 4, 5]).group('registration_stage') }

end

也許ruby的group_by對於您要完成的工作來說是一個更好的選擇,因此您可以從范圍中刪除該group

class User < ActiveRecord::Base

    scope :incomplete_onboarding, -> { where(registration_stage: [1, 2, 3, 4, 5]) }

end

然后當您調用它時,可以將其分組:

User.incomplete_onboarding.group_by { |u| u.registration_stage }

這將導致像這樣的哈希

{ 1 => [user1, user2], 2 => [user3] } 

暫無
暫無

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

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