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
has_many through inserts null primary_key with accepts_nested_attributes_for #17015
Comments
I've made an executable test case for this: https://gist.github.com/al2o3cr/245b9592acd5dfde66bd with logs for both cases. This appears to reproduce on 4.1.3 through 4.2.0.rc2 as well. |
Have to call it a night, but here's my findings so far:
This change: which shipped in 4.1.2 altered the behavior of When I've got some time, I plan to attempt a git bisect to figure out where this changed. |
Git bisect points the finger at 8cb48ab. Still need to determine how this changed things. |
Looks like calling
After 8cb48ab, however, the sequence looks like this:
The fix does not appear to be straightforward, as reinstating the
|
In the off chance that it is helpful I will provide my local fix for this issue. When I was investigating this bug I noticed that the def student_ids=(new_student_ids)
student_parents_attributes = []
new_student_ids = new_student_ids.to_a.map(&:to_param).select(&:present?).map(&:to_i)
# remove missing students
student_parents.each do |student_parent|
student_parents_attributes << { id: student_parent.id, _destroy: true } unless student_parent.student_id.in? new_student_ids
end
# add new students
new_student_ids.each do |new_student_id|
student_parents_attributes << { student_id: new_student_id } unless student_parents.select { |student_parent| student_parent.student_id == new_student_id }
end
self.student_parents_attributes = student_parents_attributes if student_parents_attributes.present?
end |
Tracked down the fix for this. The tests added in 8cb48ab fail if the Will PR the solution in the next couple days. |
It's the same issue as in #16494. I started looking at it some time ago and wrote a failing test case: https://github.com/pranas/rails/tree/fix_collection_singular_ids= @al2o3cr I see you got the solution figured out so I'll leave it to you to make the PR (unless you don't want to?). Feel free to pull my test case. |
It works since 4.2.1. |
A change between v4.1.1 and v4.1.2 causes a has_many through association to be inserted with a null primary_key when using the "association_ids=" setter. This only happens when accepts_nested_attributes_for is used (might have something to do with autosave callbacks).
This is a problem when the database uses "null false" restrictions on the primary_key. Is this expected behavior and if so is there a fix?
Models
Queries
Migration
The text was updated successfully, but these errors were encountered: