我有一个用户模型。每个用户都有与其相关的餐厅名称。我有一个视图(index.html.erb),它显示所有用户。
我想在这个视图中根据current_user和其他用户在降序中共有多少家餐馆来订购用户.(事实恰恰相反!)
例如。
User1 (current_user)去过McDonalds,汉堡王,Arby's
User2去了伊瓦尔家
User3去过McDonalds,汉堡王
当User1加载索引视图时,用户应该显示的顺序是:
User1 (3/3餐厅匹配)
User3 (2/3餐厅配对)
User2 (0/3餐厅匹配)
我的User.rb文件
def compare_restaurants
self.restaurants.collect
end我的users_controller.rb
def index
@users = User.all.sort_by {|el| (el.compare_resturants & current_user.compare_resturants).length }
end发布于 2011-02-18 06:36:10
如果您已经完全开始使用sort_by,那么您可以直接否定这些数字:
def index
@users = User.all.sort_by { |el|
-(el.compare_resturants & current_user.compare_resturants).length
}
end此技巧只起作用,因为您正在按数值进行排序。如果要对字符串进行排序,那么就必须使用这样的方法:
reverse_sorted = a.sort_by { |x| something(x) }.reverse但这将涉及到数组的额外副本和reverse所做的额外工作。在这种情况下,您应该使用带有反向比较逻辑的完整sort。
如果您试图使用sort_by来避免为每个比较计算一些昂贵的东西,并且对一些非数字的东西进行排序,那么您总是可以使用带有显式Schwartzian变换的sort来计算昂贵的东西一次。
发布于 2011-02-18 03:51:10
在控制器里对它们进行排序。
my = User.find_by_id this_user # Or however you're getting "the current user"
@users = User.all.-([my]).sort do |a, b|
common_with_a = (my.restaurants & a.restaurants).length
common_with_b = (my.restaurants & b.restaurants).length
common_with_a <=> common_with_b
end..。但是,如果您计划让用户开始对各种列进行排序,或者大量地反向排序,那么您应该在Javascript中实现您的排序,这样您就可以减少页面重新加载的次数和随后必须执行的数据库访问次数。
https://stackoverflow.com/questions/5037271
复制相似问题