0

I have a random webpage link below that works if you reload the page each time and don't hit the "back" button on your browser. Is there a way to get this to be a new link every click by using Ruby/Rails? Or would this be something I'd have to use JS or something for? Reason I ask is because I have no experience with any other languages. Maybe there is a way to auto_reload the webpage every 10 seconds or something similar?

Webpage Model

class Webpage < ActiveRecord::Base
 validates_presence_of :link

 def self.randomize_webpages
  all.shuffle.first.link
 end
end

WebpagesController

def index
  @webpages = Webpage.all
end

View

<%= link_to 'Take Me Anywhere But Here', @random_page %>

CSV

CSV seeder for Webpage

link
http://www.buzzfeed.com
http://www.reddit.com
http://boston.com
http://phys.org
http://www.popsci.com
http://www.technologyreview.com
http://techcrunch.com
View Index.html.erb
John
  • 443
  • 8
  • 19

1 Answers1

1

In your controller, you could set @random_page within index:

def index
  @random_page = Webpage.randomize_webpages
end

This would call this method to return a random link on each load of index:

class Webpage < ActiveRecord::Base
 validates_presence_of :link

 def self.randomize_webpages
  all.sample.link
 end
end
CDub
  • 13,146
  • 4
  • 51
  • 68
  • Right i have done that setup but my problem now is that the link remains the same if you hit the "back" button on your browser – John Jan 11 '14 at 18:44
  • In this case, you'll want to use JavaScript, though this may be a difficult problem to solve. Check this out, it may help: http://stackoverflow.com/questions/6359327/detect-back-button-click-in-browser – CDub Jan 11 '14 at 18:49
  • Thanks I will check that out and see if I can implement it. In the meantime the following is a rough solution but it works if placed in appropriate view: – John Jan 11 '14 at 18:51