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.
Just, find with offset
I hope it helps
Edited:
Since
Answer.order("RAND()").first
works fine with MySQL, also you can useAnswer.order("RANDOM()").first
with PostgreSQL, or with offset you can do it with confidence it works.A simpler approach, in my opinion, is to use Ruby's sample method:
OR
Even better, I would eliminate your model's
random_answer
method and define theAnswersController
method as:Ruby Doc reference: http://www.ruby-doc.org/core-2.1.5/Array.html#method-i-sample