Displaying a Random Database Item to View — Rails

不羁的心 提交于 2019-12-12 01:56:07

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/27002114/displaying-a-random-database-item-to-view-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!