繁体   English   中英

在Rails before_save方法中大写多个属性

[英]Capitalizing more than one attribute in a Rails before_save method

我想使用before_save方法将模型实例的first_namelast_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM