我正在尝试按名称字母顺序对@users进行排序。我该怎么做?
@users.person.name
编辑: 这是我解决这个问题的方法: @users.排序!{ |a, b| a.person.name <=> b.person.name }
谢谢 num8er
对您的解决方案进行一次观察。如果您使用#sort!
而不是#sort
则需要有一个很好的理由;#sort
最好,除非您需要#sort!
。
请考虑以下代码:
1 个测试 = %w(c a b( 2 p test.sort # => ['a', 'b', 'c'] 3 p 测试 # => ["c", "a", "b"] 4 p 测试排序!# => ['a', 'b', 'c'] 5 p 测试 # => ['a
', 'b', 'c']如果您不知道为什么第 5 行显示的值与第 3 行不同,那么我建议您在这样做之前完全避免使用#sort!
。 否则,您可能会创建一些非常难以找到的错误。
您可以使用sort
,但这需要首先获取所有用户。如果有很多用户,这可能会消耗大量内存。
相反,您可以在数据库中进行排序,并根据需要按顺序获取它们。
@users = User
.joins(:person) # join by the model name
.order("people.name") # order by the table name
# find_each is more efficient than each for large sets
@users.find_each do |user|
...do something with each user...
end
您可以将其放在一个范围内,以便在任何地方使用。
class User
scope :by_name, ->() { joins(:person).order("people.name") }
end
# Find the first 10 users, ordered by their name.
@users = User.by_name.limit(10)