- Read Tutorial
- Watch Guide Video
As we continue to build out our controller, let's walk through how to add private methods that are accessed only from the specific controller.
Going back to our tasks_controller.rb
, you can see that the many methods in it such as create, update and destroy can be called from other classes or APIs, and this is exactly what you want. On the other hand, there are some methods that you don't want anyone else to access for security and workflow reasons. For example, the set_task
method finds a task from the database, and you wouldn't want everybody to be able to do that. So, mark such methods as private so that they are only used within that class by other methods and are not visible outside the class.
In our class, this is the reason for putting both set_task
and task_params
methods as private. Now, let's write the logic for these methods.
def set_task @task = Task.find(params[:id]) end
This method will find the task based on the given id, and load it in the task
variable.
We are making this method available to other methods like show, edit, update and destroy with ourbefore_action
call right at the beginning.
In the next method, task_params
, we are going to give a list of fields that we want to accept as values from the user through a form.
So, our code should be:
def task_params params.require (:task).permit (:title, :description, :project_id, :completed, :task_file) end
Essentially, this code allows users to input the values for the above fields in a form. If you're unsure of the fields, it's a good idea to open your schema file to see how each field is named.
After implementing the code your file should look something like this: