Search code examples
ruby-on-rails-3randomsqlite3-ruby

Pulling 4 random ID's (rows) from a Sqlite table and posting the data on a separate page in Ruby on Rails?


I know the title is ridiculously long, but I'm in need of some assistance with Ruby on Rails and Sqlite3.

I had originally thought doing something like 4.times { (0..??).to_a.shuffle } would print a number between 0 and ?? (e.g. 20) four times, but all it did for me (in the rails console) was print the number '4' once.

Any idea on how I can do this successfully in Ruby on Rails by accessing a database table called "bullets" and using embedded ruby (.erb)?


Solution

  • You can pull 4 random rows from sqlite using a query like:

    select * from bullets order by random() limit 4;
    

    So the AREL syntax is:

    Bullet.select(:id).order('random()').limit(4).collect { |b| b.id }
    => [24, 6, 57, 37]