您應該可以通過在has_many :has_seens
關聯中添加:order
子句來完成此操作,以在創建日期之前對其進行排序。然後使用一個協會擴展到聯想本身定義的方法:
class User < ActiveRecord::Base
has_many :has_seens, :order => 'created_at DESC' do
def recent(count=10)
all(:limit => count)
end
end
end
現在你可以使用user.has_seens.recent
讓看到的最近的十部電影。可選地,通過不同的計數例如user.has_seens.recent(25)
。
順便說一句,我認爲viewings
是一個不太尷尬的協會名稱比has_seens
!
編輯:就個人而言,我會安排一個Viewing
東西加盟模式,就像這樣:
class User < ActiveRecord::Base
has_many :viewings
has_many :movies, :through => :viewings
end
class Viewing < ActiveRecord::Base
belongs_to :user
belongs_to :movie
default_scope :order => 'created_at DESC'
# Recent n viewings for any user
named_scope :recent, lambda { |count| { :limit => count }}
end
class Movie < ActiveRecord::Base
has_many :viewings
has_many :users, :through => :viewings
end
我用的Viewing
模型默認的範圍,但你可以指定如果在默認情況下查看應該由創建日期以外的其他某個屬性進行排序,則可以對關聯進行排序。
現在你可以這樣做:
# 10 most recent viewings for everyone
recent = Viewing.recent(10)
是否有您所使用的'Movie'模型作爲連接表由'指定一個特別的原因:source'選項?當你想要一個單獨的連接模型時,通常使用':has_many:through'關聯。 – 2010-03-16 20:26:24