- Read Tutorial
- Watch Guide Video
Rails gives you quite a few ways to set default values in an application.
One way to do is to go to the schema file and list the default values against each parameter. Though this looks easy, I'm not really a fan of this option because I don't like to do a SQL code implementation when I can make a method call from my model instead. Also, if I use this option, I have to do a database migration and there are a few extra steps involved in this process. Further, if I want to make changes in the future, I would rather change a line of code in the model since I feel I have a lot more control over it.
The second way is to use a method callback in the model file. To do this, type in the following code:
The first line of code tells the application to run the method called set_defaults
after the object is initialized. If you come to the method, you can see the code self.percent_complete
. Here, self
means calling the object, which in this case, is a specific project. In the second part of this code, we are telling the application to set a default value to the percent_complete
parameter of the object.
The next part of the code, ||=
is called a conditional assignment operator. What this operator does is it looks into the percent_complete
parameter to see if it has any value. If a value already exists, then it skips the record. In other words, this operator sets a value of 0.0
only if the value is nil.
Let's try this in the browser now. Restart your server, go the browser, create a new project and leave the percent_complete field empty. When you click on the Create Project button, you can see that the value for percent_complete
is automatically set to 0.0
.
Next, I'm going to make another change to the code. I don't want the user to explicitly set the value for my percent_complete field, rather I want an automatic task to do this job. So, I first remove the percent_complete
field from my form.html.erb
file. If I go the browser now and create a new project, I will have only the title and description fields displayed to me.
If you click on the Create Project
button, you can see in the next page that the default value appears for the percent_complete
parameter, and this means, our code worked!
One last thing in this lesson is the use of after_initialize
. There are a whole lot of method callbacks that you can use, and one of them is after_create
. The problem with this callback is that it may wipe out values that you may not want to, and this can cause problems later. So, it's better to use after_initialize
instead of after_create
when you want to set the default values.