Reputation: 981
I have model of subscription to news topic, witch has secret field for subscription/unsubscription:
class TopicSubscription < ActiveRecord::Base
include WithSecret
...
end
here is code of module, which generates subscription secret
module WithSecret
extend ActiveSupport::Concern
included do
attr_accessible :secret
validates_presence_of :secret
before_create :gen_secret
end
def gen_secret
begin
o = [('a'..'z'),('0'..'9')].map{|i| i.to_a}.flatten
code = (0...128).map{ o[rand(o.length)] }.join
end while self.class.send(:"find_by",{secret: code})
self.send("secret=",code)
end
end
problem if that gen_secret hook never fires and I always get validation error. What is purpose of such strange behavior?
Upvotes: 0
Views: 625
Reputation: 29860
before_create
fires after validation. Use before_validation :gen_secret, on: :create
instead.
Upvotes: 2