[英]Capitalizing more than one attribute in a Rails before_save method
我想使用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
然后,您可以將要大寫的屬性添加到可capitalizable
數組中。 我使用類似的代碼對某些模型中的所有String進行upcase
,只是為了保持數據清潔的一致性。
這只是@engieeringmnky答案的另一個版本:
before_save :capitalize_attributes
private
def capitalize_attributes
self.attributes.select{ |a| ["first_name","last_name"].include? a }.each do |attr, val|
self.send("#{attr}=", val.try(:strip).try(:capitalize))
end
end
在@engineersmnky的基礎上,進一步關注 Rails 4+(更多信息 ):
應用程序/模型/關注/ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.