Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk update attribute on multiple models in ActiveRecord?

I have a simple has_many association, and I want to change an attribute from public to private the associated object. What's the best way to do this:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

user = User.first #=> #<User...>
user.posts.count #=> 100
# something like this:
user.posts.bulk_update_attribute("privacy", "private") #=> 1 DB call
like image 506
Lance Avatar asked Oct 26 '10 16:10

Lance


1 Answers

I believe you are looking for update_all.

In your example, you'd rewrite it to be something like

Post.update_all("privacy = 'private'", ["user_id = ?", user.id])

Or as @jenjenut233 points out

user.posts.update_all("privacy = 'private'")
like image 174
theIV Avatar answered Oct 24 '22 22:10

theIV