- Read Tutorial
- Watch Guide Video
In this guide, we are going to learn to save values in the backend of a nested resource for a Rails app.
Let's start by going to our tasks_controller.rb
. Here, we are going to make a change to the class name to make sure that the TaskController
is nested under Projects
.
Our code should be:
class Projects::TaskController < ApplicationController
Next, we want our Projects
methods to be available to all the methods in this file. To this end, we are going to set this is in another before_action
call.
before_action :set_project, only: [:show, :new, :create, :edit, :update, :destroy]
If you notice, I've made projects available to all public methods in this file.
Next, let's create our set_project
method.
def set_project @project = Project.find(params[:project_id]) end
The only difference between the set_project
and set_task
method is that the first takes params[:project_id]
as the parameter while the second takes params[:id]
as its parameter respectively. This difference is because we want to know the project id associated with a particular task. If you remember, the URL we want, it should be in the format .com/projects/5/tasks/2
. So, we use this code to find the project with the corresponding project_id.
The last part we are going to change is inside the create
method. Add this code right after we initialize the task
variable.
@task.project_id = @project.id
In this line, we know the project id from the before_action
call, and we are setting it to the task. If you notice, we are not asking a user to enter the project_id
of a task because the user may or may not know this. Hence, we are finding this id and setting it to a task through the code.
Another change is to make the form available to both the task and project, and this is why we change the first line of our code to include project as well in our _form.html.erb
file.
Lastly, we want the new and edit forms to render the partial, so go to edit.html.erb
and new.html.erb
inside the tasks folder, and type the following code.
<%= render 'form' %>
That's everything we need to do, and we will keep going in the subsequent lessons.