I have an SQL statement like this. Is this type of statement possible entirely or mostly in ActiveRecord?
UPDATE users
JOIN (
SELECT user_id, count(*) AS num
FROM posts
GROUP BY user_id
) AS counts ON users.id = counts.user_id
SET users.publications = counts.num
WHERE users.publications != counts.num;
How can I do the JOIN from a table "users" to the results of a SELECT subquery that's been grouped by one of the selected values?
Can I alias the join so i can compare values between the
userstable and the join?
I'm having a hard time searching for this because I don't know the term to call a JOIN that's not a join between tables, but a join from a table to a specially formatted group of results. I don't think AR's magic can work with that, but i'm not sure.
I'm assuming that your models are related like user has_many posts and post belongs_to user.
In this case, you would be better advised to add a column called posts_count and change the relationship in User to
has_many :posts, counter_cache: true.This will keep a count of a user's posts in the User model, in the posts_count field, automatically updated whenever a user creates a new post. If you really need it to be called
publications, adddef publications; posts_count; endto the user model.When adding this counter cache, you will need to initialize it for all the existing users. This is a one-time operation, so you can do it from the Rails console like this:
User.all.each{|u| u.reset_counters(u.id, :posts_count)}.