0

I want to have a button which goes to a random user on my site. I am using the friendly_id gem so the URLs are, for example, /users/dean and I've also set it up so its /dean.

I'm guessing I would add something similar to this in my routes.rb file:

match '/users/random' => 'users#index'

And then some extra code in the user controller?

How would I go about doing this?

Many thanks.

2 Answers2

0

I would have a specific action random in the user controller and localize the logic for choosing a user there. Return a redirect to the route to that user from that action. I would prefer this over complicating the index action with extra logic to handle a different action.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • I see so in the routes, it would be something like `match '/users/random' => 'users#random'`? Could you say what code I would need to put in the user controller? I'm only new to Rails and it will help others out :) –  Jul 03 '11 at 18:55
0

I'd do this:

Define a class method random on User model (or in a module that's included into your model if you'd want to reuse it for other models later).

class User
  def self.random
    offset = rand(count)
    first(:offset => offset)
  end
end

Other ways of getting a random record, if performance becomes an issue.

Add a random action in your UsersController like this

def random
  redirect_to User.random
end

And finally create a route

match '/users/random' => 'users#random'
Community
  • 1
  • 1
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • Just a quick question, how can I do it so it ONLY shows users with content in `image_url`? –  Jul 05 '11 at 16:11