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_before_type_cast is not working with accepts_nested_attributes_for and has_many association #48301

Closed
mateusnava opened this issue May 25, 2023 · 1 comment
Labels

Comments

@mateusnava
Copy link

Steps to reproduce

class User < ApplicationRecord
  has_many :schools

  accepts_nested_attributes_for :schools
end

class School < ApplicationRecord
  belongs_to :user
end
  • Create a User with a School:
User.create!(name: "user 1")
User.first.schools.create!
  • Assigns an attribute with the wrong format (degree_issued_at in my example):
user.assign_attributes(school_attributes: [{id: 1, degree_issued_at: "2020-30-30"}]

Expected behavior

I expected to see degree_issue_at: "2020-30-30" in the attributes_before_type_cast

Actual behavior

> user.schools.first.attributes_before_type_cast
=> {"user_id"=>1, "id"=>1, "name"=>nil, "degree_issued_at"=>nil}

System configuration

Rails version: 7.0.5

Ruby version: 3.0.1

Possible fix

Change the method ActiveModel::Type::Value#changed? to:

  def changed?(old_value, new_value, new_value_before_type_cast)
    return true if old_value.nil? && new_value.nil? && new_value_before_type_cast.present?
    ...
  end

I only could reproduce this issue with has_many, accepts_nested_attributes_for, and a persisted record with nil in the attribute.

@rails-bot
Copy link

rails-bot bot commented Aug 23, 2023

This issue has been automatically marked as stale because it has not been commented on for at least three months.
The resources of the Rails team are limited, and so we are asking for your help.
If you can still reproduce this error on the 7-0-stable branch or on main, please reply with all of the information you have about it in order to keep the issue open.
Thank you for all your contributions.

@rails-bot rails-bot bot added the stale label Aug 23, 2023
@rails-bot rails-bot bot closed this as completed Aug 30, 2023
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

1 participant