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?
You can get a count of the users using User.count
.
In your template, you can add something like
There are <%= User.count %> users.
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.
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?
精彩评论