ruby on rails - callback before_save seems not working -


i need execute method name before record saved in database, seems not working

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 

console

=> 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">  

you need change

self.firstname.titleize  + " " + self.lastname.titleize 

to

self.firstname = self.firstname.titleize self.lastname  = self.lastname.titleize 

explanation: didn't change anything, concatenate values.

but want use name method name-representation. i'd suggest new method validation.

it this:

def titlelize_names   self.firstname = self.firstname.titleize   self.lastname  = self.lastname.titleize end 

and before_save must call :titlelize_names, of course.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -