开发者

Rails: Prioritize/sort collection of records

I have a Post model that belongs to a single category and author. Users may create "favorites" for categories and authors. 开发者_运维问答 How can I most efficiently query a list of all posts, but with the visitor's preferred categories and/or authors sorted to the top?

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


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)

Alternate: less number of queries, but user model fetches data from 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)

This code is not tested, but gives the idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜