让我们看看DB特定选项。
class Article
# ...
def self.random(limit: 10)
scope = Article.where(published: true)
# postgres, sqlite
scope.limit(limit).order('RANDOM()')
# mysql
scope.limit(limit).order('RAND()')
end
end
Article.random
询问数据库,以获得10个随机记录我们。 因此,让我们看看如何将添加一个选项排除一些记录:
class Article
# ...
def self.random(limit: 10, except: nil)
scope = Article.where(published: true)
if except
scope = scope.where.not(id: except)
end
scope.limit(limit).order('RANDOM()')
end
end
现在Article.random(except: [1,2,3])
将获得10条记录,其中ID是不[1,2,3]
。
这是因为rails中的.where
返回一个可链接的作用域。例如:
> User.where(email: '[email protected]').where.not(id: 1)
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 AND ("users"."id" != $2) [["email", "[email protected]"], ["id", 1]]
=> #<ActiveRecord::Relation []>
,我们甚至可以在这里传递范围:
# cause everyone hates Bob
Article.random(except: Article.where(author: 'Bob'))
为什么一个DB具体的解决方案是在这里一个不错的选择见Rails Quick Tips - Random Records。
来源
2016-09-25 14:44:44
max
我该如何添加“AND?”我想要一个发布的地方:真,不在范围内。 – josh
更改where子句。我编辑了答案。 – inye
请参阅@ Max关于链接哪里调用通常更清洁的建议:'Article.where(published:true).where.not(id:ids_to_exclude).order(“RANDOM()”)' – gmcnaughton