I have 2 models
class Variant < ActiveRecord::Base
belongs_to :product
with_options :if => :is_active? do |p_active|
p_active.validates :avatar, :presence => true
end
with_options :if => :isnt_diavoleria? do |p_active|
p_active.validates :color, :presence => true
end
def is_active?
self.product.active
end
def isnt_diavoleria?
a = (self.is_active? and self.product.section_id != 5)
a
end
end
class Product < ActiveRecord::Base
has_many :variants, :autosave => true
accepts_nested_attributes_for :variants
end
If i change the attribute section_id or active of a product and save, the validations of the model variant are executed with the old values of section_id and active.
Why?
How can i do the validations with the new values?
The problem is that by default a pair of
has_manyandbelongs_toassociations don’t know that they are the inverse of each other. So when youthen inside your validation, the variant goes
and actually fetches that from the database again, which obviously doesn’t have your unsaved change.
You should be able to fix this by adding the
:inverse_offlag to your associations, i.e.One day rails will have an identity map which should make this sort of stuff less error prone (it is in rails 3.1 but disabled because of subtle associated bugs if i remember correctly)