Kevin Brown
Kevin Brown

Reputation: 12650

Rails return number of users

I'm learning rails and I'm just trying to get the basics down.

I just installed devise and created a home controller. If I want to get the number of users (just return the number of records in the db), what should I do from the home controller? It should interact with a model, right? Can the home controller interact with the users model and the home model? Or is that bad practice?

I know I could do a simple google search for this, but I have a lot of questions and Stackoverflow is legit. :)

Take it a step further?

How would I get a 'live feed' so that the count changes on the home page when a record is added?

Upvotes: 2

Views: 2664

Answers (3)

slhck
slhck

Reputation: 38711

Something like

User.all.length
User.count

should work, where the first one is highly inefficient and the second one much better Rails style.

It's not necessarily a bad idea to directly access that. Why not?

Upvotes: 0

Dogbert
Dogbert

Reputation: 222248

You can get a count of the users using User.count.

In your template, you can add something like

There are <%= User.count %> users.

Upvotes: 7

d11wtq
d11wtq

Reputation: 35318

Your controllers can interact with any number of models and if they couldn't, you wouldn't be getting much done ;)

As for the "live feed", that's tricky. You probably want to use something like Comet.

Upvotes: 0

Related Questions