我想使用 before_save
方法将模型实例的 first_name
和 last_name
大写。我当然可以这样做:
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
然后您只需将想要大写的属性添加到 capitalized
数组即可。我使用类似的代码来大写
某些模型中的所有字符串,只是为了保持数据干净一致。
关于ruby-on-rails - 在 Rails before_save 方法中将多个属性大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26244488/