Take the 2-minute tour ×

Say I have a model called User that has the following parameters: favorite_color, favorite_animal, and lucky_number. The user fills in the form containing only favorite_color and favorite_animal. When the form is submitted, I want to run a function that takes the color and animal into account and comes up with a lucky_number. How do I insert a value to the post values without the user filling out the form - how and where do I implement this?

Thank you!

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Since the lucky_number won't be known until after the favorite_animal and favorite_color are already recorded, it would be impossible to send it along with the post request. Try using a


that looks something like this:

before_validation_on_create :generate_lucky_number

def generate_lucky_number
     self.lucky_number = self.favorite_animal.length + self.favorite_color.length

This function just sets the lucky number to the combined length of the strings stored for the favorite color and favorite animal, and will set it before saving the user to the database.

share|improve this answer
PERFECT. Thank you so much! –  yuval Feb 26 '10 at 23:19

You could build it into your controller logic, or place the code in your model in one of the following callbacks:

share|improve this answer
but how would I go about adding lucky_number into my post parameters? –  yuval Feb 26 '10 at 21:25
Why do you need to add it to your post parameters? In the before_validation* call check for the value and fill it from the user model if it does not exist. Assuming you have the correct association between User and Post models you can call self.user to get the User instance in a Post instance. –  Harish Shetty Feb 26 '10 at 21:39
I guess I was unclear. I do not have a Post model. I wanted to add the lucky_number data to my user (via a POST request). self.user seems promising, or maybe self.lucky_number? I'll give it a try –  yuval Feb 26 '10 at 21:49
+1, this is the right way to do it. I offered a more specific example in another response. –  Austin Fitzpatrick Feb 26 '10 at 23:02
thank you very much for the answers –  yuval Feb 26 '10 at 23:19

Your Answer


