views:

26

answers:

2

Hi,

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!

+2  A: 

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

meagar
but how would I go about adding lucky_number into my post parameters?
yuval
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.
KandadaBoggu
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
+1, this is the right way to do it. I offered a more specific example in another response.
Austin Fitzpatrick
thank you very much for the answers
yuval
+2  A: 

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

before_validation_on_create

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
end

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.

Austin Fitzpatrick
PERFECT. Thank you so much!
yuval