将 sql 查询转换为rails activerecord

发布于 2024-10-29 07:01:43 字数 230 浏览 1 评论 0原文

我有一个简单的问题。我无法计算出此 sql 查询的 Rails 等效项:

select COUNT(description) from reports where user_id = current_user;

实际上我想计算总数。特定用户登录其帐户时发布的报告,而不是所有用户发布的所有报告。 我也无法弄清楚应该如何传递当前登录用户的 user_id 以便获得所需的结果。 请帮忙。

I have a simple problem . I am not able to figure out the rails equivalent for this sql query:

select COUNT(description) from reports where user_id = current_user;

Actually I want to count the total no. of reports posted by a particular user when logged in his account and not the all reports posted by all users.
I am also not able to figure out that how should I pass the user_id of the current user logged in so that I can get the required result.
Please Help.

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

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

发布评论

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

评论(2

挽你眉间 2024-11-05 07:01:43

像这样的东西:

current_user.reports.count

Something like:

current_user.reports.count
爱,才寂寞 2024-11-05 07:01:43

在 Rails 2 中

,如果您在用户模型中定义了 has_many :reports

count = current_user.reports.first(:select => "COUNT(description) as count").count

如果模型中未定义 has_many

count = Report.first(:select => "COUNT(description) as count",
             :conditions => {:user_id => current_user.id}).count

但是 current_user.reports.select{ |report| report.description }.count 就足够了,尽管它会产生不同的查询。 (Select * from reports where ..),然后计算数组的计数。

但在 Rails 3 中,这相当容易。

如果您在用户模型中定义了 has_many :reports

count = current_user.reports.count(:description)

否则

count = Report.where(:user_id => current_user.id).count(:description)

请参阅 Rails 指南 了解 Rails 3 AR 计算查询。

In Rails 2

If you have defined has_many :reports in User model.

count = current_user.reports.first(:select => "COUNT(description) as count").count

If has_many is not defined in the model,

count = Report.first(:select => "COUNT(description) as count",
             :conditions => {:user_id => current_user.id}).count

But current_user.reports.select{ |report| report.description }.count is enough though it produces a different query. (Select * from reports where ..) and then take the count of the array.

But in Rails 3, it is quite easy.

If you have defined has_many :reports in User model.

count = current_user.reports.count(:description)

otherwise

count = Report.where(:user_id => current_user.id).count(:description)

Refer Rails guide for Rails 3 AR calculation queries.

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