When using accepts_nested_attributes_for
in my project, if any of my nested attributes' hash has a nil
value then I get an error saying,
NoMethodError: undefined method 'with_indifferent_access' for nil:NilClass`.
If I replace that nil value with an empty HashWithIndifferentAccess
then the nested entity gets created with NULL
values.
Is there any way to avoid trying to create an entity if the attributes hash is nil or should I just delete that attributes hash from the hash?
class User < ActiveRecord::Base
has_one :user_info, autosave: true
accepts_nested_attributes_for :user_info
end
class UserInfo < ActiveSupport::Base
belongs_to :user
has_one :user_identifier, autosave: true
accepts_nested_attributes_for :user_identifier
end
class UserIdentifier < ActiveSupport::Base
belongs_to :user_info
end
When I try to create a new User
:
hash = {follower_count: 10 , user_info_attributes: { user_identifier_attributes: nil } }
usr = User.new(hash)
If any of my attribute hashes is nil
(like user_identifier_attributes
above) then I get:
NoMethodError: undefined method `with_indifferent_access' for nil:NilClass
But then if I set nil
attributes to a new HashWithIndifferentAccess
in my initialize
method then the entity gets created with NULL
values.
class UserIdentifier < ActiveSupport::Base
belongs_to :user_info
def initialize(attributes = nil)
attributes[:user_identifier_attributes] = attributes.delete(:user_identifier) || HashWithIndifferentAccess.new
end
end
hash = {follower_count: 10 , user_info_attributes: { user_identifier_attributes: nil } }
usr = User.new(hash)
usr.user_info.user_identifier # => #<UserIdentifier:0x0000559a30c32380 id: nil, user_info_id: nil, name: nil, value: nil>