views:

61

answers:

1

I have a model that sets one of its attributes based off of a form parameter that a user submits. The model is a child resource to a parent resource Home. A hypothetical example is the following:

A class Person has an age attribute. The user submits a birthdate as an HTTP POST parameter and from that, I need to derive the age of the user. So I'd do something like this:

  @home.people.build(:name => params[:name], :birthdate => params[:birthdate])

Rails would barf on that for obvious reasons, complaining it doesn't know what the attribute birthdate is. What's the proper way of going about this?

Is it possible to use the build constructor with the supplied solution so that my foreign key relations are also setup properly? If not, what's a better way to work around this problem?

+2  A: 

You can use a virtual attribute to accept the parameter from your POST and then calculate the value you want for your column (untested):

class Person < ActiveRecord::Base
  def birthdate=(birthdate)
    self.age = Time.now - Date.new(birthdate) # [1]
  end
end

[1] not the right syntax -- you'd have to parse the date according to the format of your parameter -- but you get the idea

zetetic
Is it possible to call the build method afterwards so that the child resource is properly linked to its parent?
randombits
Sure -- try it out in the console
zetetic