Foolish Chap
Foolish Chap

Reputation: 765

Rails ActiveRecord query for most recent viewed resources

I recently made the following models:

class User < ActiveRecord::Base
  has_many :resources
  has_many :resource_views, :through => :user_resource_views, :source => 'Resource'
end

class Resource < ActiveRecord::Base
  belongs_to :user
  has_many :resource_views, :through => :user_resource_views, :source => 'Resource'
end

class UserResourceView < ActiveRecord::Base
  attr_accessible :resource_id, :user_id
  belongs_to :resource
  belongs_to :user_id
end

Now, I want my home#index action to set @resources to the current_user's most recently viewed resources. How would you advise I proceed? Perhaps something similar to current_user.resource_views.find(:all, :order => 'created_at')?

In SQL, I would do something like:

SELECT * 
FROM Resource 
WHERE id IN (SELECT * FROM UserResourceView WHERE user_id = current_user.id)

... but then the ORDER BY created_at, hmmm

I'll be periodically adding progress updates throughout the day until I figure it out.

Upvotes: 0

Views: 734

Answers (1)

Benedikt Deicke
Benedikt Deicke

Reputation: 610

Given you're on Rails 3.x, what you're looking for is probably something like this:

class User < ActiveRecord::Base
  has_many :resources
  has_many :resource_views, :class_name => 'UserResourceView'
  has_many :viewed_resources, :through => :resource_views, :source => :resource

  def recently_viewed_resources
    viewed_resources.order('user_resource_views.created_at DESC')
  end
end

class Resource < ActiveRecord::Base
  belongs_to :user
  has_many :resource_views, :class_name => 'UserResourceView'
end

class UserResourceView < ActiveRecord::Base
  attr_accessible :resource_id, :user_id
  belongs_to :resource
  belongs_to :user_id
end

And to access the collection in your controller:

current_user.recently_viewed_resources

Upvotes: 2

Related Questions