简体   繁体   中英

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 without the user filling out the form - how and where do I implement this?

Thank you!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM