【问题标题】:Rails model scope and groupRails 模型范围和组
【发布时间】:2016-01-28 20:03:26
【问题描述】:

我想获取所有注册阶段为 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

【问题讨论】:

    标签: sql ruby-on-rails-4 activerecord scope group-by


    【解决方案1】:

    也许 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] } 
    

    【讨论】:

    • 谢谢,虽然我希望范围自然地以组的形式提供数据,但这很有效,但也许这并不理想。
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多