ROR ActiveRecord manipulation attribut avec un before_update de rappel
-
21-09-2019 - |
Question
Ce code produit un ActiveRecordError :
Callbacks doit être un symbole indiquant la méthode à appeler, une chaîne à évalué, un bloc à invoquer, ou un objet de répondre à la fonction de rappel Procédé ».
before_update :check_instock, :unless => Proc.new { |inventory| inventory.needed.nil? }
def check_instock
if needed < amount
instock = true
else
instock = false
end
end
Ce code est placé dans mon modèle d'inventaire, je suis en train de gérer une certaine logique avant d'appeler @ inventory.update_attributes (contrôleur). Auparavant, je l'appelais @ inventory.update_attributes plusieurs fois, ce qui a entraîné code travaillé , mais pas de façon succincte.
Vive!
La solution
before_update :set_instock, :unless => :inventory_not_needed?
private
def set_instock
self.instock = (needed < amount) ? true : false
end
def inventory_not_needed?
needed.nil?
end
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow