Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How to fetch the last 10 records from activities of each friends with a user?


  • Please log in to reply
3 replies to this topic

#1 Logesh

Logesh

    Signalman

  • Members
  • 14 posts

Posted 26 September 2013 - 07:09 AM

I have a user model and each user will have many friends and i have another table where the activities of each user is saved. Consider an example

 

user1 has friends say user2 and user3

 

id    name

 

1     user1

2     user2

3     user3

 

In activities table i have 

 

user_id   friend_id    activity                     date_of_activity

 

    2              1          playing                     2013-09-13 10:20:03.037149

    1              2          watched movie        2013-09-15 04:46:59.523838

    2              1          studied                     2013-09-18 06:27:20.239551

    3              1          playing                     2013-09-21 10:20:03.037149

    3              1          studied                     2013-09-24 06:27:20.239551

    3              1          studied                     2013-09-26 10:20:03.037149

    1              3          playing                     2013-09-27 10:20:03.037149

 

Now i have to get the recent two activities that the user1 is involved in with each friend

 

for example

 

user_id   friend_id    activity                     date_of_activity

 

    1              2          watched movie        2013-09-15 04:46:59.523838

    2              1          studied                     2013-09-18 06:27:20.239551

    3              1          studied                     2013-09-26 10:20:03.037149

    1              3          playing                     2013-09-27 10:20:03.037149

 

I hope the above would have explained the scenario clearly. How can i fetch those records. How can i query efficiently to fetch if there are 1000 friends? please help me.



#2 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 26 September 2013 - 03:06 PM

re: sorting 

In your model, have something like

 

 

# order by date descending, latest first
default_scope -> { order('date_of_activity DESC') }

  • lazarus likes this

#3 robzdc

robzdc

    Passenger

  • Members
  • 4 posts

Posted 09 October 2013 - 10:22 PM

Maybe this can help you

 

https://www.ruby-too...public_activity



#4 Kushal M

Kushal M

    Passenger

  • Members
  • 1 posts

Posted 14 October 2013 - 11:34 AM

default order in activity model,

 

default_scope -> { order('date_of_activity DESC') }

 

and then,

 

my_result = Activity.where(["user_id = ? or friend_id = ?", id,id]).limit(2)






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users