简体   繁体   English

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

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

I'd like to capitalize the first_name and last_name of my model instances using the before_save method. 我想使用before_save方法将模型实例的first_namelast_name大写。 Of course I could do this: 我当然可以这样做:

before_save do 
  self.first_name = first_name.capitalize
  self.last_name = last_name.capitalize
end

But I'd much rather alter the two attributes in one fell swoop. 但是,我宁愿一次改变两个属性。 Is there a way to select certain columns in my model and apply the desired method to them? 有没有一种方法可以选择模型中的某些列并对其应用所需的方法?

You could do something like this 你可以做这样的事情

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

Then you can just add the attributes you want capitalized to the capitalizable array. 然后,您可以将要大写的属性添加到可capitalizable数组中。 I use a similar code to upcase all Strings in certain models just to keep data clean an consistent. 我使用类似的代码对某些模型中的所有String进行upcase ,只是为了保持数据清洁的一致性。

This is just an another version of @engieeringmnky's answer: 这只是@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

Building on @engineersmnky's answer further for Rails 4+ with Concerns (more here ): 在@engineersmnky的基础上,进一步关注 Rails 4+(更多信息 ):

app/models/concerns/model_hooks.rb 应用程序/模型/关注/ 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

then in your models: 然后在您的模型中:

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