2014-05-10 45 views
0

PostgreSQL要求random()MySQL要求rand()有沒有辦法用Rails的方式來寫兩個數據庫的查詢?隨機的任何數據庫Rails

在本地主機上,我使用PostgreSQL,在MySQL的發展,該查詢:

@texts = Text.where('status is true and id != ?', @text.id).limit(3).order("RANDOM()") 
+0

使用[隨機類](http://www.ruby-doc.org/core-2.1.1/Random.html)計算紅寶石? – hd1

回答

2

如下嘗試,

case ActiveRecord::Base.connection.adapter_name 
    when 'PostgreSQL' 
    @texts = Text.where('status is true and id != ?', @text.id).limit(3).order("RANDOM()") 
    else 
    @texts = Text.where('status is true and id != ?', @text.id).limit(3).order("rand()") 
    end 
1

您可以使用抵消你的優勢,找到一個隨機記錄獨立於您的數據庫。

Text.offset(rand(Text.count)).first