Elijah Hall
Elijah Hall

Reputation: 115

Rails: How to update all through ActiveRecord_Relation

I have two related models through has_one like this:

class Asset
  has_one :device

class Device
  belongs_to :asset

I have an ActiveRecord_Relation of assets like this:

assets = Asset.all

I need to update a field in every Device for every asset. I do NOT want to create an array of every associated device since it will be very inefficient. I have tried things like:

assets.joins(:device).update_all( {:device=>{:my_field=>6} )

Upvotes: 1

Views: 3234

Answers (2)

Elijah Hall
Elijah Hall

Reputation: 115

The solution is this:

assets = Asset.some_scope.some_other_scope
devices = Device.where("devices.asset_id IN (?)", assets.select(:id))
devices.update_all("devices.my_field=?", 6)

This uses a single database query to update all associated devices through their relationship with assets.

Upvotes: 2

Vasfed
Vasfed

Reputation: 18444

You can use SQL:

assets.joins(:device).update_all(["devices.my_field=?", 6])

or if that field depends on others:

assets.joins(:device).update_all("devices.my_field=assets.other_field")

Upvotes: 2

Related Questions