开发者

Create a 'Random User' button on my Rails 3 web app

开发者 https://www.devze.com 2023-03-16 20:46 出处:网络
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 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.


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'


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消