开发者

Getting a random record from a set of results

@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|开发者_StackOverflow中文版
    format.html { redirect_to(@picture) }
    format.json { render :json => @picture }
end

I get the following error: NoMethodError in PicturesController#next private method `rand' called for []:ActiveRecord::Relation

Instead of

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

I also tried

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

and get this error instead: ActiveRecord::StatementInvalid in PicturesController#next Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0.6704131293122307' at line 1: SELECT pictures.* FROM pictures LIMIT 1 OFFSET 0.6704131293122307

What am I doing wrong, or how do I go about getting a random record from the array of results? Thanks in advance.


convert rand result to integer like this:

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


In ruby 1.9.2, you can just do:

@picture.sample
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜