Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

attributes_for does not use initialize_with like the docs states it does #1606

Open
ezekg opened this issue Dec 15, 2023 · 2 comments
Open
Assignees
Labels

Comments

@ezekg
Copy link

ezekg commented Dec 15, 2023

Description

According to the docs, attributes_for constructs a hash using initialize_with, but this isn't actually the case.

Is this a bug, or incorrect documentation?

Reproduction Steps

Reproduction script: https://gist.github.com/ezekg/7738249c671e48c0372884c847e2559f

Expected behavior

The initialize_with callback is used during creation of the attributes_for hash.

Actual behavior

The initialize_with callback is not used for the attributes_for hash.

System configuration

factory_bot version: v6.4.2
rails version: v7.1.2
ruby version: v3.2.2

@mike-burns
Copy link
Member

Good catch. The documentation is incorrect.

But since you bring it up I should ask: did you want attributes_for to use initialize_with? Is there a compelling use case for it?

@ezekg
Copy link
Author

ezekg commented Dec 27, 2023

@mike-burns, I do similarly to what the reproduction script shows. Essentially, I want to not assign attributes if the sentinel value is present, because I'm tracking assignment of these attributes (where even nil is significant). Perhaps there's a better way, but using sentinel values was the easiest solution I came up with. But since attributes_for doesn't actually utilize initialize_with, I have to add superfluous attributes_for assignments to avoid assigning the sentinel values on the actual record (i.e. in this case, account and environment are superfluous for nested attributes since the associations have defaults that would kick in if the sentinel values weren't present). Here's a comment where I talk to myself about this (lol).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants