Rails 返回用户数量

发布于 2024-11-17 07:04:43 字数 304 浏览 1 评论 0原文

我正在学习 Rails,我只是想了解基础知识。

我刚刚安装了设备并创建了一个家庭控制器。如果我想获取用户数(仅返回数据库中的记录数),我应该从家庭控制器做什么?它应该与模型交互,对吧? home 控制器可以与 users 模型和 home 模型交互吗?或者这是不好的做法?

我知道我可以对此进行简单的谷歌搜索,但我有很多问题,而且 Stackoverflow 是合法的。 :)

更进一步?

我如何获得“实时反馈”,以便在添加记录时主页上的计数发生变化?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

故事未完 2024-11-24 07:04:43

您可以使用 User.count 获取用户计数。

在您的模板中,您可以添加类似的内容

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

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

In your template, you can add something like

There are <%= User.count %> users.
黑白记忆 2024-11-24 07:04:43

您的控制器可以与任意数量的模型交互,如果不能,您将无法完成很多工作;)

至于“实时反馈”,这很棘手。您可能想使用类似 Comet 的东西。

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.

指尖上的星空 2024-11-24 07:04:43

像这样的东西

User.all.length
User.count

应该可以工作,第一个效率非常低,而第二个则更好的 Rails 风格。

直接访问它不一定是一个坏主意。为什么不呢?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文