Rails - 显示随机记录但不是当前记录 [英] Rails - Show A Random Record But Not The Current

查看:53
本文介绍了Rails - 显示随机记录但不是当前记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在博客文章的末尾,我想显示指向另一篇随机文章的预告链接.显然,此链接不应该是当前帖子本身的预告片.

At the end of a blog post I would like to display a teaser link to another random post. Obviously this link should be NOT a teaser for the current post itself.

我已经知道如何选择随机帖子,但仍有可能是预告链接是当前帖子的链接.我想不通,我怎么能排除这种情况.

I figured already out how to choose a random post, but there is still the chance that the teaser link is a link to the current post. I couldn't figure out, how can I exclude this case.

这是我的控制器:

def show
    @post = Post.find(params[:id])
    @staff_pickrandom = Post.where(staff_pick:true).order("RANDOM()").limit(1)
end

我对 Rails 还很陌生,我仍然在为基本的东西苦苦挣扎.对不起,如果这是一个简单的.非常感谢您的帮助!!!

I am quite new to Rails and I am still struggling with basic stuff. Sorry, if this is an easy one. Thank you so much for helping out!!!

更新:我正在使用 Rails 3.2 和 "friendly_id" Gem.

UPDATE: I am using Rails 3.2 and the "friendly_id" Gem.

推荐答案

使用 order('RANDOM()').limit(1) 是正确的开始方式,因为最好让DB 选择随机记录,而不是获取大量 id,然后让 Ruby 从数组中采样.为了避免选择您当前使用的帖子,请使用 where.not 来排除该帖子

Using order('RANDOM()').limit(1) is the right way to start since it is better to let the DB choose a random record, than fetching a large set of ids, and letting Ruby sample from an array. In order to avoid choosing the post you are currently on use where.not to exclude that post

 Post.where(staff_pick: true).where.not(id: @post.id).order('RANDOM()').limit(1)

 Post.where(staff_pick: true).where('id != ?', @post.id).order('RANDOM()').limit(1)

这篇关于Rails - 显示随机记录但不是当前记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆