Nested Routes in Rails3
In this article I am going explain nested resouces in rails . I hope you all familiar with REST in rails I am not going to discuss REST nature here.Here just consider we two resouces named as Projects and Tasks , here I am assuming that every task is related to certain Project and without project there is no task. So I will do make association has_many between Projects and Tasks .it will look like following
class Project < ActiveRecord::Base
attr_accessible :name
has_many :tasks ,:dependent => :destroy
end
class Task < ActiveRecord::Base
attr_accessible :name
belongs_to :project
end
generally our routes.rb file is like the following
routes.rb
-----------------
resources :projects
resources:tasks
so lets we modify the routes as following
resources :projects do
resources :tasks
end
that’s it REST will do the magic for us . so now we need to concern about how to create task by following REST full routes new_task_path wont work here , it will rise an error , so we must take care while using routes here, do not worry I will tell how to do this creating new task with using the following line
<%= link_to 'New Task', new_project_task_path(@project) %>
it will open form for creating new task , it will look like this and I have done small changes that to create new task I have modified target file , please observe it
<%= form_for([@project,@task]) do |f| %>
<div class="field">
<%= f.label :project_id %><br />
<%= f.text_field :project_id %>
</div>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and the tasks controller new action and create action are look like the following
def new
@project = Project.find(params[:project_id])
@task = Task.new
end
<br/>
def create
@project = Project.find(params[:project_id])
@task = Task.new(params[:task])
respond_to do |format|
if @task.save
format.html { redirect_to project_path(@project), notice: 'task was successfully created.' }
end
end
end
and we can write delete link as follows
<%= link_to "Delete task", project_task_path(@project, @task), :confirm => "Are you sure you want to delete this task?", :method => :delete %>
and also you can edit task by using following path
<%= link_to 'Edit task', edit_project_task_path(@project,@task) %>
I hope this will help you to give some idea nested routes with rails .I welcome your comments on this article so that i can improve further .thank you
Thanks Ratnakar V