Hassan Javeed
Hassan Javeed

Reputation: 464

Group activity items

I have the following table structure for storing activity items

id, trackable_id, trackable_type, owner_id, owner_type

where trackable_id and trackable_type tells me on what object(entity) the action is performed on. For example if a User with id=1 likes a Picture with id=1

id, trackable_id, trackable_type, owner_id, owner_type

1,       1,            Picture,      1,        User

Similarly another user can like the same picture. In my news feed, I can easily display the activities performed by the users, however I would like to achieve something like this:

John and katy likes Picture.

instead of

John likes Picture
Kay  likes Picture.

I guess the way to go is to do a group by based on trackable_id and trackable_type but it returns me one row(expected result of group by). I have not used group_concat before, does it help in this kind of situation? Thanks!

Upvotes: 1

Views: 78

Answers (3)

Nisarg
Nisarg

Reputation: 3282

Hey you can use Like this

CONCAT(GROUP_CONCAT( user_name SEPARATOR 'AND' ),' LIKES PICTURES')

Demo

Upvotes: 2

Konstantin Rudy
Konstantin Rudy

Reputation: 2257

Looks like you are using polymorfic associations (if no - then you should be using it). Your method will look like the following:

def liked_by_string
  user_names = users.collect(&:name).to_sentence # => "John, Katty, Mark and Pete"

  "#{user_names} like the Picture"      
end

Upvotes: 0

Akhil
Akhil

Reputation: 2602

Yes it helps.

Refer this

GROUP_CONCAT(columnName SEPARATOR ' AND ')

Upvotes: 0

Related Questions