大厦@ engineersmnky的回答进一步为Rails 4+与Concerns(更多here):
应用程序/模型/关注/ model_hooks .RB
module ModelHooks
extend ActiveSupport::Concern
included do
before_save :capitalize_attributes
end
def capitalize_attributes
self.attributes.each do |attr,val|
# if the attribute only has spaces, then this will store nil in the DB
self.send("#{attr}=",val.strip.capitalize) if self.capitalizable_attrs.include?(attr) && !val.nil?
end
end
end
然后在你的模型:
class Trail < ApplicationRecord
include ModelHooks
def capitalizable_attrs
["name"] # return an array of attributes you want to capitalize
end
end
这实际上是在将数据转换为SQL查询之前修改数据。这仍然只包含在一个INSERT/UPDATE语句中 – MrYoshiji 2014-10-07 20:20:38
不知道'downcase'是否大写字符串。你确定你想要做什么? – Surya 2014-10-07 20:21:36
@Surya对不起。修改代码以反映问题 – 2014-10-07 20:22:18