【问题标题】:Ruby on Rails get all attributes for uniq User by nameRuby on Rails 按名称获取唯一用户的所有属性
【发布时间】:2018-10-28 02:21:45
【问题描述】:

如何按名称对用户进行分组并仅获取每个名称的最新用户,

order(create_at: :desc)

我已经按名称对我的用户进行分组,但我不能只获取每个名称的最新信息:

User.group(:id, :name).select(:id, :name, :created_at)

[编辑 01]

现在我正在尝试获取 uniq 用户以及最新的用户: 有效!

User.order(upadted_at: :desc).uniq{ |u| u.name }

【问题讨论】:

    标签: ruby-on-rails ruby group-by null ruby-on-rails-5


    【解决方案1】:

    试试这个:

    User.select([:id, :name]).order(created_at: :desc).group(:id, :name)

    User.select([:id, :name]).order(:created_at).reverse_order.group(:id, :name)
    

    【讨论】:

      【解决方案2】:

      您可以查看active record documentation 了解更多信息,但您可以试试这个:

      # This will give you the SELECT DISTINCT "users"."name" FROM "users" 
      User.distinct.pluck(:name).take(2)
      
      # You can also try this to order by created_at
      User.select(:name).order(created_at: :desc)
      
      # You can also take the one that appears first in the most recent 
      User.select(:name).order(created_at: :desc).take(1)
      

      你也应该检查这个other answer

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-03
        • 2013-02-04
        • 2011-09-22
        • 1970-01-01
        相关资源
        最近更新 更多