代码之家  ›  专栏  ›  技术社区  ›  Sniggerfardimungus

Rails:如何找到()特定字段中唯一的所有记录?

  •  10
  • Sniggerfardimungus  · 技术社区  · 17 年前

    我有一个“请求”对象列表,每个对象都具有相当正常的activerecord质量。请求表与带有联接表“games_requests”的games表相关联,因此请求具有request.games数组。

    问题是,是否有办法查找最后n个唯一请求,其中唯一性由games列和其他几个列定义,但具体忽略其他列(如请求用户的名称?)

    我看到了类似“find(:all,:limit=>5,:include=>[:games,:stage])这样的语法,但它返回的是重复的。

    谢谢

    编辑:

    Games.find(
        :all, :limit => 5,
        :include => [:games, :requests],
        :group => 'games, whatever, whatever_else'
    )
    

    …给出了一个SQL错误:

    Mysql::Error: Unknown column 'games' in 'group statement': SELECT * FROM `games`  GROUP BY games
    

    我对我认为适合我的项目的东西做了一些修改;获取请求列表而不是游戏等:

    Request.find(
        :all, :order=>"id DESC", :limit=>5,
        :include=>[:games],   #including requests here generates an sql error
        :group=>'games, etc'  #mysql error:  games isn't an attribute of requests
        :conditions=>'etc'
    )
    

    我想我必须使用:join=>选择这里。

    3 回复  |  直到 7 年前
        1
  •  9
  •   chaos    17 年前
    Games.find(
        :all, :limit => 5,
        :include => [:games, :requests],
        :group => 'games, whatever, whatever_else'
    )
    
        2
  •  6
  •   James Chevalier    12 年前

    请尝试Rails uniq_by。它还可用于关联并返回数组。

    @document = Model.uniq_by(&:field)

    更多 Detail

        3
  •  0
  •   Codebeef    17 年前

    我认为您可以使用find_by_sql和GROUP by来实现这一点:

    Games.find_by_sql("SELECT * FROM games GROUP BY user_id")
    
    推荐文章