0

我最近做了以下模型:

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

现在,我希望我的 home#index 操作将 @resources 设置为 current_user 最近查看的资源。你会建议我如何进行?也许类似于 current_user.resource_views.find(:all, :order => 'created_at')?

在 SQL 中,我会执行以下操作:

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

...但随后 ORDER BY created_at,嗯

我将全天定期添加进度更新,直到我弄明白为止。

4

1 回答 1

2

鉴于您使用的是 Rails 3.x,您正在寻找的可能是这样的:

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

并访问控制器中的集合:

current_user.recently_viewed_resources
于 2013-01-14T16:04:27.597 回答