2011-05-14 45 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

相關問題