2011-05-14 44 views
1
@user_id = params[:user_id] 
@picture = Picture.scoped 
if @user_id.present? 
    @picture = @picture.where("user_id not in (?)", params[:user_id]) 
end 
@picture = @picture.rand(@picture.count).first 

respond_to do |format| 
    format.html { redirect_to(@picture) } 
    format.json { render :json => @picture } 
end 

我收到以下错误: NoMethodError在PicturesController#下一 私有方法`兰特”的要求[]的ActiveRecord ::关系获得一个随机记录从一组结果

代替

@picture = @picture.rand(@picture.count).first 

我也试过

@picture = Picture.offset(rand(Picture.count)).first 

并得到这个错误,而不是: ActiveRecord :: StatementInvalid PicturesController#next Mysql2 ::错误:您的SQL语法错误;检查对应于你的MySQL服务器版本使用附近的“0.6704131293122307”在1号线正确的语法手册:SELECT pictures * FROM pictures LIMIT 1 OFFSET 0.6704131293122307

我在做什么错了,还是我怎么去从结果数组中获得随机记录?提前致谢。

回答

3

转换兰特结果为整数这样的:

@picture = Picture.offset(rand(Picture.count).to_i).first 
2

在红宝石1.9.2,你可以做:

@picture.sample 
+0

没有它要求@picture是行的集合获取已从数据库?如果他只需要返回一行,那么获取所有内容然后选择一个并不好;) – 2011-05-14 21:23:38

+0

@Andrian我同意。我只是想替换他的麻烦线。 – sawa 2011-05-14 21:27:16

+0

这是有效的,但根据我的评论,我标记为阿德里安的最佳答案。多谢你们! – areyling 2011-05-14 21:32:41

相关问题