Rails: last three comments with unique users

what would I put in the named area: by_unique_users so that I can do Comment.recent.by_unique_users.limit (3) and get only one comment for each user?

class User
  has_many :comments
end

class Comment
  belongs_to :user
  named_scope :recent, :order => 'comments.created_at DESC'
  named_scope :limit, lambda { |limit| {:limit => limit}}
  named_scope :by_unique_users
end

on sqlite named_scope: by_unique_user ,: group => "user_id" works,

but it makes him worry about postgres, which is deployed at PGError production: ERROR: the column "comments.id" should appear in the GROUP BY clause or be used in an aggregate function

+3
source share
3 answers

Postgres MySQL SQLite , GROUP BY. , . , .

id name
1  foo
2  bar
2  baz

GROUP BY id. MySQL , , . .

id name
1  foo
2  bar

Postgres . , . , , , . , , , , min() max() . :select => 'min(comments.id), min(comments.some_other_column)', , user_id. : group = > 'user_id' .

Btw, min() max() , , . - , google " postgres first", postgres. mysql sqlite.

, , .

unique_comments = []
Comment.recent.each do |comment|
  unless unique_comments.find{|c| c.user_id == comment.user_id}
    unique_comments << comment
  end
  break if unique_comments.size > 2
end

3 .

+6

, Rails (From Geek Skillz).

Item.find( :all, :order => 'comments.created_at DESC', :select => 'DISTINCT user' )[0, 3]
0

:

named_scope :recent, :order => 'created_at DESC'

.

0
source

Source: https://habr.com/ru/post/1746941/


All Articles