回调before_save似乎不起作用

时间:2015-04-26 00:20:36

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我需要在将记录保存到数据库之前执行方法名称,但似乎无法正常工作

class Guest < ActiveRecord::Base
  before_save :name
  has_and_belongs_to_many :checkins
  validates_presence_of :FirstName
  validates_presence_of :LastName
  validates_format_of :FirstName, with: /^[A-Za-z\s]+$/
  validates_format_of :LastName, with: /^[A-Za-z\s]+$/

  def name
    self.FirstName.titleize  + " " + self.LastName.titleize  
  end
end

控制台

=> Guest(id: integer, FirstName: string, LastName: string, age: integer, sex: string, photo: string, address: text, mobile: integer, email: string, birthdate: date, created_at: datetime, updated_at: datetime) 
1.9.3-p547 :008 > f=Guest.new
 => #<Guest id: nil, FirstName: nil, LastName: nil, age: nil, sex: nil, photo: nil, address: nil, mobile: nil, email: nil, birthdate: nil, created_at: nil, updated_at: nil> 
1.9.3-p547 :009 > f.FirstName=" fernando "
 => " fernando " 
1.9.3-p547 :010 > f.LastName=" suarez"
 => " suarez" 
1.9.3-p547 :011 > f.save
 => true 
1.9.3-p547 :012 > Guest.last
 => #<Guest id: 9, FirstName: " fernando ", LastName: " suarez", age: nil, sex: nil, photo: nil, address: nil, mobile: nil, email: nil, birthdate: nil, created_at: "2015-04-26 00:16:38", updated_at: "2015-04-26 00:16:38"> 

1 个答案:

答案 0 :(得分:1)

您需要更改

self.FirstName.titleize  + " " + self.LastName.titleize

self.FirstName = self.FirstName.titleize
self.LastName  = self.LastName.titleize

说明:您实际上没有更改任何内容,而是连接值。

但是您可能希望使用name方法进行名称表示。所以我建议一种新的验证方法。

看起来像这样:

def titlelize_names
  self.FirstName = self.FirstName.titleize
  self.LastName  = self.LastName.titleize
end

当然,before_save必须调用:titlelize_names