将 sql 查询转换为rails activerecord
我有一个简单的问题。我无法计算出此 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的东西:
Something like:
在 Rails 2 中
,如果您在用户模型中定义了
has_many :reports
。如果模型中未定义
has_many
,但是
current_user.reports.select{ |report| report.description }.count
就足够了,尽管它会产生不同的查询。 (Select * from reports where ..
),然后计算数组的计数。但在 Rails 3 中,这相当容易。
如果您在用户模型中定义了
has_many :reports
。否则
请参阅 Rails 指南 了解 Rails 3 AR 计算查询。
In Rails 2
If you have defined
has_many :reports
in User model.If
has_many
is not defined in the model,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.otherwise
Refer Rails guide for Rails 3 AR calculation queries.