Rails:优先记录/排序记录

时间:2011-08-04 18:32:29

标签: ruby-on-rails

我有一个属于单一类别和作者的Post模型。用户可以为类别和作者创建“收藏夹”。如何最有效地查询所有帖子的列表,但访问者的首选类别和/或作者是否排在最前面?

class Post < ActiveRecord::Base

  belongs_to :category
  belongs_to :author

end

class Favorite < ActiveRecord::Base

  belongs_to :user
  belongs_to :category # favorite category
  belongs_to :author # favorite author

end

class User < ActiveRecord::Base

  has_many :favorites

end

1 个答案:

答案 0 :(得分:0)

class User < ActiveRecord::Base
  has_many :favorites

  has_many :favorite_categories, :through => :favorites, :source => :category
  has_many :favorite_authors, :through => :favorites, :source => :author
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :category # favorite category
  belongs_to :author # favorite author
end

class Post < ActiveRecord::Base
  belongs_to :category
  belongs_to :author

  named_scope :order_by_user, lambda {|user| where(
    :category_id => user.favorite_categories.map(&:id),
    :author_id   => user.favorite_authors.map(&:id)
  )}
end

user = User.first
posts = Post.order_by_user(user)

备用:查询数量较少,但用户模型从Favorite

获取数据
class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :category # favorite category
  belongs_to :author # favorite author
end

class User < ActiveRecord::Base
  has_many :favorites

  def favorite_category_ids
    Favorite.where(:user_id => self.id).select(:category_id).map(&:category_id).compact
  end

  def favorite_author_ids
    Favorite.where(:user_id => self.id).select(:author_id).map(&:author_id).compact
  end
end

class Post < ActiveRecord::Base
  belongs_to :category
  belongs_to :author

  named_scope :order_by_user, lambda {|user| where(
    :category_id => user.favorite_category_ids,
    :author_id   => user.favorite_author_ids
  )}
end

user = User.first
posts = Post.order_by_user(user)

此代码未经过测试,但提供了这个想法。