Ruby on Rails: building a model with an attribute not in a database?
I have a model that sets one of its attributes based on a form parameter that the user submits. The model is a child of the parent Home resource. A hypothetical example is as follows:
The Person class has an age attribute. The user submits the date of birth as an HTTP POST parameter and from that I need to determine the age of the user. So I would do something like this:
@home.people.build(:name => params[:name], :birthdate => params[:birthdate])
The rails on this would change for obvious reasons, complaining that he doesn't know what the attribute's date of birth is. What's the correct way to do this?
Can I use the build constructor with the supplied solution so that my foreign key relationship is set up correctly as well? If not, what's the best way to get around this problem?
a source to share
You can use a virtual attribute to take a parameter from your POST and then compute the value you want for your column (unchecked):
class Person < ActiveRecord::Base
def birthdate=(birthdate)
self.age = Time.now - Date.new(birthdate) # [1]
end
end
[1] not correct syntax - you will have to parse the date according to the format of your parameter, but you get the idea
a source to share