简体   繁体   English

如何使用 Ruby on Rails 查询计算 SQL 数组中的元素

[英]How to Count the Elements in an SQL Array using Ruby on Rails Queries

I want to count the number of elements in an array specific to a user id and then display that number.我想计算特定于用户 ID 的数组中元素的数量,然后显示该数字。 The last_viewed array keeps track of the event the user last visited. last_viewed 数组跟踪用户上次访问的事件。

The schema.db looks like this (its not the whole schema I just included what I think is necessary to solve my problem.) schema.db 看起来像这样(它不是整个模式,我只是包含了我认为解决我的问题所必需的内容。)

create_table "users", id: :serial, force: :cascade do |t|
   t.integer "last_viewed", default: [], array: true
end

I tried我试过

<%= ((Users.last_viewed.where("id = ?", current_user.id)).count) %>

but it seems to think that last_viewed is a method and not part of the Users table.但它似乎认为 last_viewed 是一种方法而不是用户表的一部分。

I know how to use real SQL but these queries in Ruby on Rails are confusing.我知道如何使用真正的 SQL 但 Ruby on Rails 中的这些查询令人困惑。 Essentially I want to turn this SQL code into something that works on Ruby.本质上,我想将这个 SQL 代码转换成适用于 Ruby 的代码。

SELECT array_length(u.last_viewed, 1) 
FROM users u 
WHERE u.id = <user's id>;

last_viewed is a column in the users table, which acts as a method in an instance of the User model. If you don't have an instance of that class you can't use that method unless you defined your own. last_viewed是用户表中的一列,它充当用户 model 实例中的一个方法。如果您没有该 class 的实例,则不能使用该方法,除非您定义了自己的方法。

To get the total last_viewed from the user with id equal to current_user.id you can simply use find , invoke that method and as it returns an array you can use size/count/length to have the total of elements:要从 id 等于current_user.id的用户那里获取last_viewed总数,您可以简单地使用find ,调用该方法,当它返回一个数组时,您可以使用 size/count/length 来获得元素总数:

Users.find(id: current_user.id)&.last_viewed&.length

& is used to avoid a NoMethodError exception in case a user with that id doesn't exist in the database and find returns nil. &用于在数据库中不存在具有该 ID 的用户并且find返回 nil 时避免 NoMethodError 异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM