lavapj
lavapj

Reputation: 399

Rails routing -- how to route to item with random id number

I have a very simple rails app. I generated scaffolding for Card which among other things allows me to go to a specific route for record with id http://app.com/cards/3.

When I go to root http://app.com I want to be routed to show a random card with random id, say "X" (http://app.com/cards/X)

I'm pretty sure this is wrong, but I attempted to add the following in the Cards Controller:

def random
  @card = Card.order("RANDOM()").first
end

And then add in routes.rb:

root :to => 'cards#random'

The error I get in browser when I try to go to route:

Template is missing

Missing template cards/random, application/random with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: * "/Users/patricia/Documents/Repos/coastguard-quiz-rails/app/views"

And finally when I run "rake routes" I get:

    cards GET    /cards(.:format)          cards#index
          POST   /cards(.:format)          cards#create
 new_card GET    /cards/new(.:format)      cards#new
edit_card GET    /cards/:id/edit(.:format) cards#edit
     card GET    /cards/:id(.:format)      cards#show
          PUT    /cards/:id(.:format)      cards#update
          DELETE /cards/:id(.:format)      cards#destroy
     root        /                         cards#random

Could someone please guide me in the right direction? Thanks in adv.

Upvotes: 0

Views: 820

Answers (3)

Thomas Klemm
Thomas Klemm

Reputation: 10856

def random
   ids = Card.pluck(:id)
   ids.sample
end

You could select and map all existing ids to an array (that what pluckdoes), and sampling a single id from the array of existing ids. This way you make sure a card with this id is present.

Depending on your table size this might be even more efficient than loading all records into memory.

Upvotes: 1

Jason Kim
Jason Kim

Reputation: 19041

Change the random method to this.

def random
  @card = Card.find(rand(Card.count)+1)
end

Your route looks fine.

As for Template is missing error, it's probably because you are misssing random.html.erb or random.html.haml in views/cards/ directory

Upvotes: 0

Catfish
Catfish

Reputation: 19294

You basically need to redirect to the card page that you find. Currently you're receiving a template error because it's looking for the view /views/cards/random.html.erb but it doesn't exist.

Try this:

def random
  @card = Card.order("RANDOM()").first
  redirect_to card_path(@card)
end

Upvotes: 2

Related Questions