There is a method in the model:
def set_hash unless self.api_key self.api_key = Digest::SHA1.hexdigest ("shop_" + self.id.to_s) self.save! end end and before_save :set_hash , but this does not work, because apparently self.id = null
There is a method in the model:
def set_hash unless self.api_key self.api_key = Digest::SHA1.hexdigest ("shop_" + self.id.to_s) self.save! end end and before_save :set_hash , but this does not work, because apparently self.id = null
I would not recommend using callbacks in general and for a specific task in particular. They are too difficult to manage. If, nevertheless, to use kollbek, then in this case after_create can approach. At the time of its call, the model will already have an id and, unlike after_save it will not be called whenever the record is saved. In the third rails, I remember, the call to save from callbacks called after saving was forbidden (to avoid looping)
However, I would rather define the api_key method:
def api_key @api_key ||= Digest::SHA1.hexdigest ("shop_#{self.id}") end This will allow not to store redundant data in the database. If api_key needs to be searched, it is better to implement a separate SearchObject .
Recommend on Growing Rails Applications in Practice
The before_save before_save triggered before saving, when id is not yet, moreover, there is no sense in saving the model in this callback, since save will go after this event. You'd better not use before_save , but after_save , when the id is already in the model.
Source: https://ru.stackoverflow.com/questions/517181/
All Articles