Rails 3 - Run an Update in a Model
I have an employee table with particular columns:
employee_nbr, first_name, last_name and employee_nbr_name
I need to somehow populate the employee_nbr_name column with the data from the other columns like this:
1234 - First Last (employee_nbr space dash first_name space last_name)
First question is where should I do this? In the mo开发者_JS百科del or controller when the employee is being created?
Secondly, can anyone help with how to format it?
Thanks!
like jklina says, put it in your model. but use interpolation so even with nil values your app won't crash:
def generate_employee_nbr_name
self.employee_nbr_name = "#{employee_nbr} - #{first_name} #{last_name}"
end
In your model you can do the following:
class Employee < ActiveRecord::Base
before_save :generate_employee_nbr_name
private
def generate_employee_nbr_name
self.employee_nbr_name = "#{employee_nbr} - #{first_name} #{last_name}"
end
end
That will string them together and set the column so when the record saves it will save the string as well.
精彩评论