Displaying a Random Database Item to View — Rails

2019-08-27 17:29发布

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: enter image description here

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.

2条回答
叼着烟拽天下
2楼-- · 2019-08-27 18:08

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.

查看更多
3楼-- · 2019-08-27 18:11

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

查看更多
登录 后发表回答