Skip to content

Keep prefix options in first_or_create and first_or_initialize - #478

Open
afurm wants to merge 1 commit into
rails:mainfrom
afurm:keep-prefix-in-first-or-create
Open

afurm wants to merge 1 commit into
rails:mainfrom
afurm:keep-prefix-in-first-or-create

Conversation

@afurm

@afurm afurm commented Oct 17, 2026

Copy link
Copy Markdown

first_or_create and first_or_initialize don't work on nested resources. For a resource like

class StreetAddress < ActiveResource::Base
  self.site = "http://example.com/people/:person_id"
  self.element_name = "address"
end

this raises ActiveResource::MissingPrefixParam: person_id prefix_option is missing when nothing matches:

StreetAddress.where(person_id: 1, street: "Main").first_or_create(country: "Australia")

and first_or_initialize returns a record with empty prefix_options, so it can't be saved.

find_every only stored the query options in the collection's original_params and dropped the prefix options, so the record built from original_params never got person_id. This keeps the prefix options in original_params, so the new record gets them back through load, the same way StreetAddress.new(person_id: 1, ...) does. original_params for resources without a prefix stays the same.

While there, both methods called original_params.update(attributes), which changed the collection's original_params in place, so the attributes leaked into a later where on the same collection. They now use merge.

Collections built by find(:all) only kept the query options in
original_params, so calling first_or_create or first_or_initialize on a
nested resource built a record without its prefix options. Creating it
raised MissingPrefixParam, and an initialized record could not be saved.

Both methods also called Hash#update on original_params, so the
attributes passed to them leaked into later where calls on the same
collection.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant