How to add parameters to a ruby on rails post?
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 withou开发者_Go百科t the user filling out the form - how and where do I implement this?
Thank you!
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.
You could build it into your controller logic, or place the code in your model in one of the following callbacks:
- before_validation
- before_validation_on_create
- before_validation_on_update
精彩评论