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

StackOverflow https://stackoverflow.com/questions/11165171

Pergunta

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)?

Foi útil?

Solução

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] 

Outras dicas

If you are looking to for an array of random numbers from 0 to n, try:

4.times.collect {rand(20)}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top