Reputation: 309
I've researching the answer to this question for a while and can't figure it out. I'm trying to build a view that displays a random item from the database (I'm eventually going to make a future implementation to do it via button-click). I have no idea whats wrong.
I have a scaffold called Answers that just displays text. In my Answers Controller, I built a custom method called random:
def index
@answers = Answer.all
end
def show
end
def random
# @randitem = @items[rand(items.count)]
@randanswer = Answer.random_answer
end
In my models:
class Answer < ActiveRecord::Base
def self.random_answer
Answer.order("RAND()").first
end
end
Finally, in my views/random.html.erb:
<!--Doesn't work-->
<%= link_to @randanswer.answer_response, link_to_answer(@randanswer) %>
The a folder screenshot:
I'm just about at my wits end with this, which is frustrating because I feel like this is a very simple problem. Any suggestions or helpful resources would be appreciated.
Upvotes: 0
Views: 329
Reputation: 12427
A simpler approach, in my opinion, is to use Ruby's sample method:
def self.random_answer
Answer.all.sample
end
OR
def self.random_answer
Answer.order(:column_name).sample
end
Even better, I would eliminate your model's random_answer
method and define the AnswersController
method as:
def random
@randanswer = Answer.all.sample
end
Ruby Doc reference: http://www.ruby-doc.org/core-2.1.5/Array.html#method-i-sample
Upvotes: 1
Reputation: 5229
Just, find with offset
# Rails 4
def self.random_answer
offset = rand(Answer.count)
Answer.offset(offset).first
end
# Rails 3
def self.random_answer
offset = rand(Answer.count)
Answer.first(:offset => offset)
end
I hope it helps
Edited:
Since Answer.order("RAND()").first
works fine with MySQL, also you can use Answer.order("RANDOM()").first
with PostgreSQL, or with offset you can do it with confidence it works.
Upvotes: 1