Answer the question
In order to leave comments, you need to log in
How to increment a field in a table by user?
I'm trying to make bookmarks with the ability to change the order. There are users with a one-to-many relationship to bookmarks.
Added an integer priority field to bookmarks.
I roughly understand how to increment a field in a common heap in a migration:
orBookmark.update_all('priority = priority + 1')
ActiveRecord::Base.transaction do
ActiveRecord::Base.connection.execute('SET @pri := 0;')
ActiveRecord::Base.connection.execute('UPDATE bookmarks SET priority = ( SELECT @pri := @pri + 1 ) ORDER BY updated_at ASC;')
end
user_id: 1, priority:1
user_id: 2, priority:2
user_id: 1, priority:3
user_id: 2, priority:4
user_id: 1, priority:1
user_id: 2, priority:1
user_id: 1, priority:2
user_id: 2, priority:2
Answer the question
In order to leave comments, you need to log in
1) Retrieve all users.
2) For each user, we go over the bookmarks and assign a priority
To be honest, it is not clear why to look for a solution using the database. If the database is really huge (GB / TB of data), then we run step 2. into multiple threads.
https://apidock.com/rails/ActiveRecord/Base/increment!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question