Monday, May 10, 2010

Check - It Works!

I figured it out. I have attributes in my Stat database table that the user doesn't provide input for. The value, for the hidden attributes, is gotten from the other attributes that the user does provide input for.

What I did:

In the Model:

before_validation :cache_virtual_columns
def total_points
((twopfgm * 2)+(threepfgm * 3)+(ftm * 1))
end
def field_goal_percent
sprintf("%0.3f", ((twopfgm+threepfgm)/(twopfga+threepfga.to_f)))
end

private
def cache_virtual_columns
self.total_points = total_points
self.field_goal_percent = field_goal_percent
end

In the Form:

%= f.hidden_field :total_points
%= f.hidden_field :field_goal_percent


When a new Stat record is created, it checks the Model and before doing validations does the cache_virtual_columns method. cache_virtual_columns has the total_points and field_goal_percent DB columns equal the value in their method. This updates the Stat record to contain values for each attribute.

No comments: