rails - assign preexisting record as nested association while updating nested attributes

482 Views Asked by At

I am not using a rails form as this is all coming from an XML that I am parsing. For my requirement, I need to assign an existing record as nested association while at the same time, updating selected attributes of that association.

My models are the following:

class Listing < ApplicationRecord
  belongs_to :user, inverse_of: :listings
  accepts_nested_attributes_for :user
end

class User < ApplicationRecord
  has_many :listings, inverse_of: :user
  belongs_to :agency, inverse_of: :users
end

class Agency < ApplicationRecord
  has_many :users, inverse_of: :agency
end

Now, to assign an existing user record, my listing params should be

params = { user_id: 1230 }

To include user record attribute changes, my listing params should be:

params = { user_attributes: { agency_id: 3453 } }

Then of course I do the assignment and save:

listing.assign_attributes(params)
listing.save

Using only the former params doesn't allow me to do the agency_id update in the same database transaction; while using the latter params creates a new user record.

My original attempt was to merge the two param sets somehow:

params = { user_attributes: { id: 1230, agency_id: 3453 } }

This resulted in the following:

ActiveRecord::RecordNotFound: Couldn't find User with ID= 1230 for PropertyListing with ID=

Sidenote: I would like to be able to support both update and create actions with the same params set.

Since that didn't work I tried another hybrid:

params = { user_id: 1230, user_attributes: { agency_id: 3453 } }

But this one also created a new user with the correct agency_id, while ignoring the user_id attribute.

Is there a way to assign the existing User.find(1230) while updating the same user's agency_id in the same ActiveRecord DB request and params set?

0

There are 0 best solutions below