0

I have this method which I want me to fetch the most recent activity_id for the corresponding user_id from the model UserActivity that keeps track of all the user activities and from that get the description of the activity_id from another model Activity. The function works fine but at times throws bugs as "Not able to find activity_id". May be there could be a better way to implement this or Am I doing something wrong here ?

def last_activity(date, user_id)
  active_id = UserActivity.find(:all, :conditions => ["Date(updated_at) <= ? and user_id = ?", date, user_id]).last.activity_id
  text = Activity.find(active_id).description
end

The Schema of the model UserActivity is as follows : enter image description here

Please help me get this fixed. Thanks !!

Ruby version 1.8.7, Rails 2.1.2

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Mithun Sasidharan
  • 20,572
  • 10
  • 34
  • 52
  • Does that bug occur to you when there are no values to be shown? In which case `last.activity_id` might be irrelevant. Does the answer in here help you in any way? : http://stackoverflow.com/questions/4966430/model-find1-gives-activerecord-error-when-id-1-does-not-exist – sarath Feb 20 '12 at 07:20

2 Answers2

2

Assuming you have following models

class User
  has_many :user_actvities
  has_many :activities, :through => :user_actvities, 
    :order => "user_actvities.id"
end

class UserActivity
 belongs_to :user
 belongs_to :activity
end

class Actvity
  has_many :user_actvities
  has_many :users, :through => :user_actvities
end

To get the current user's last activity

current_user.activities.last

This relies on the fact that UserActivity object with the max id is the latest activity.

If you update the UserActivity after creation, you have to change the order clause of the association, i.e.

has_many :activities, :through => :user_actvities, 
  :order => "user_actvities.updated_at"
Harish Shetty
  • 64,083
  • 21
  • 152
  • 198
0

Either the query is not finding any match or some records might be having null values for activity_id column, following code should work

user_activity = UserActivity.find(
   :all, :conditions => ["DATE(updated_at) <= ? AND user_id = ? AND activity_id IS NOT NULL", date, user_id], 
   :order => "updated_at DESC", :limit => 1).first
text = Activity.find(user_activity.active_id).description rescue nil
nkm
  • 5,844
  • 2
  • 24
  • 38
  • UserActivity and Activity are two different models completely... UserActivity keeps track of all user activities and in the function when I give a date and a user id I want that to fetch the most recent activity of the user within the date and from that activity_id I go to the activity model to fecth its description ! – Mithun Sasidharan Feb 20 '12 at 07:39