-
I need help understanding the behavior using Ruby and Mongoid 8.0 with I have a Customer model (simplified) class Customer
include Mongoid::Document
field :name, type: String
field :nickname, type: String
embeds_many :business_settings, class_name: 'BusinessSettings', cascade_callbacks: true
accepts_nested_attributes_for :business_settings
delegate(*business_settings_attributes, to: :current_business_settings, allow_nil: true)
def self.business_settings_attributes
business_settings_attrs = BusinesSettings.attribute_names.flat_map { |a| [a, "#{a}=", "#{a}?", "#{a}_changed?"] }
customer_attrs = Customer.attribute_names.flat_map { |a| [a, "#{a}=", "#{a}?", "#{a}_changed?"] }
attrs = (business_settings_attrs - customer_attrs)
attrs << 'role_or_custom_role_id'
attrs << 'role_or_custom_role_id='
attrs << 'status'
attrs << 'status='
attrs.map(&:to_sym)
end
.... and the another model (simplified) class BusinessSettings
include Mongoid::Document
attr_accessor :role_or_custom_role_id
field :role, type: String
field :status, type: String
embedded_in :customer
before_validation :set_role
.... The problem is that when I try to update a customer, changing the virtual attribute customer.role_or_custom_role_id = 'new_id'
customer.save the callback customer.role_or_custom_role_id = 'new_id'
customer.status = 'new_status'
customer.save the code above does execute the callback and the embedded is updated Whit Mongoid 7.5 changing only the virtual attribute NOTE: It's like in Mongoid 8.0, it doesn't detect changes in the embedded model when only the Can someone help me understand? 🙏🏼 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hello, I'm sorry this one was so mysterious! It's a consequence of #5787, which fixed a significant performance issue with validations on associations. So, you're right, that the issue has to do with class BusinessSettings
include Mongoid::Document
def role_or_custom_role_id=(value)
# move the logic from `set_role` to here...
end
# ...and then remove the `before_validation` callback?
end |
Beta Was this translation helpful? Give feedback.
-
@jamis thanks a lot, this solution works for me |
Beta Was this translation helpful? Give feedback.
Hello,
I'm sorry this one was so mysterious! It's a consequence of #5787, which fixed a significant performance issue with validations on associations.
So, you're right, that the issue has to do with
attr_accessor
. Validations are now only run on associated records if the records have changed. Because setting a value viaattr_accessor
does not mark the record as changed (that only happens when persistable fields are modified), the validation (and before_validation) callbacks aren't being invoked. To work around this, would it be feasible for you to do something like: