1

I want to count the number of elements in an array specific to a user id and then display that number. The last_viewed array keeps track of the event the user last visited.

The schema.db looks like this (its not the whole schema I just included what I think is necessary to solve my problem.)

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.

I know how to use real SQL but these queries in Ruby on Rails are confusing. Essentially I want to turn this SQL code into something that works on Ruby.

SELECT array_length(u.last_viewed, 1) 
FROM users u 
WHERE u.id = <user's id>;
2
  • 1
    I think correct query should be Users.where("id = ?", current_user.id)).last_viewed.count Commented Aug 4, 2020 at 5:36
  • Have you looked at using Arel to define the array_length function so you can reference it in a model? The benefits would vary, but for a very large array you would not have to retrieve it to Rails to process it. Commented Aug 15, 2020 at 15:45

1 Answer 1

1

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.

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:

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.