You need to reference self explicitly if you want to call a setter method. Otherwise you will assign to a local variable
md5 = "foo" # local variable
self.md5 = "foo" # method call, value will be stored in the instance.
Вопрос
I have a model that some record must be filled automatically after the user input.
Then I used before_save
callback, but the records will not be stored.
This is my model:
before_save :create_relation_plus_md5
has_many :bridges
attr_accessible :id, :admin_user_id, :md5, :url, :name, :cBox
validates_presence_of :name
validates_uniqueness_of :name
def create_relation_plus_md5
baseUrl = "http://www.mysite.com/?id="
digest = Digest::MD5.hexdigest("#{name}#{id}#{someOtherData}")
puts "digest : #{digest}"
md5 = digest
url = "#{baseUrl}#{digest}"
# + create relations
end
The md5 and url will not be stored, I think I miss something. Maybe I must call the save
explicitly in the method?
I can do with a workaround with after_save
and call back the model manually, but naturally this create a infinite loop...
Решение
You need to reference self explicitly if you want to call a setter method. Otherwise you will assign to a local variable
md5 = "foo" # local variable
self.md5 = "foo" # method call, value will be stored in the instance.