Rails 3, ActiveRecord, PostgreSQL - “.uniq” command doesn't work?

后端 未结 4 1316
轮回少年
轮回少年 2020-12-09 17:51

I have following query:

Article.joins(:themes => [:users]).where([\"articles.user_id != ?\", current_user.id]).order(\"Random()\").limit(15).uniq
<         


        
4条回答
  •  不思量自难忘°
    2020-12-09 18:00

    As the error states for SELECT DISTINCT, ORDER BY expressions must appear in select list. Therefore, you must explicitly select for the clause you are ordering by.

    Here is an example, it is similar to your case but generalize a bit.

    Article.select('articles.*, RANDOM()')
           .joins(:users)
           .where(:column => 'whatever')
           .order('Random()')
           .uniq
           .limit(15)
    

    So, explicitly include your ORDER BY clause (in this case RANDOM()) using .select(). As shown above, in order for your query to return the Article attributes, you must explicitly select them also.

    I hope this helps; good luck

提交回复
热议问题