How would I make a link that takes you to a random article on the site?

时间:2015-10-30 23:31:18

标签: ruby-on-rails ruby server

It would be exactly like Wikipedia's "Random Article" button. Takes you to a random webpage on the site.

2 个答案:

答案 0 :(得分:0)

<%= button_to "Random Article", article_path(random_article) %>

#app/helpers/application_helper.rb
class ApplicationHelper
   def random_article
      Article.order("RAND()").first.pluck(:id)
   end
end

在本文的帮助下:Random record in ActiveRecord

答案 1 :(得分:-1)

更多信息可以让您更容易回答,但有几种方法可以做到。在我看来,最好的是这样的:

routes.rb中:

resources :articles do
  get :random_article
end
#OR
get 'random_article' => 'some_controller#random_article', as: 'random_article'

articles_controller.rb

def random_article
  redirect_to article_path(Article.all.sample.id)
end

在您的页面上:

<%= link_to 'Random Article', random_article_path %>