我想使用方法将模型实例的first_name
和last_name
都大写before_save
。我当然可以这样做:
before_save do
self.first_name = first_name.capitalize
self.last_name = last_name.capitalize
end
但是,我宁愿一次改变两个属性。有没有一种方法可以选择模型中的某些列并对其应用所需的方法?
你可以做这样的事情
before_save :capitalize_attributes
private
def capitalize_attributes
capitalizable = ["first_name","last_name"]
self.attributes.each do |attr,val|
#based on comment either of these will work
#if you want to store nil in the DB then
self.send("#{attr}=",val.strip.capitalize) if capitalizable.include?(attr) && !val.nil?
#if you want to store a blank string in the DB then
self.send("#{attr}=",val.to_s.strip.capitalize) if capitalizable.include?(attr)
end
end
然后,您可以只将要大写的属性添加到capitalizable
数组中。我upcase
对某些模型中的所有String使用类似的代码,只是为了保持数据清洁的一致性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句