I have two controllers: workers and tasks.
views/workers/index contains:
<% @workers.group_by(&:name).each do |name, workers| %>
<tr>
<td><%= name %></td>
<td><%= workers.size %></td>
</tr>
<% end %>
It shows me all the workers and their number of tasks.
I want to add a another <td> that is named: “show all tasks” and shows all the tasks of worker X.
in order to do that, I think I need something like:
<td><%= link_to 'show all tasks', worker_task_path(name) %></td>
thus, I have tasks_controller:
def index
@task = Worker.where(:name => params[:id]) respond_to do |format|
format.html # show.html.erb
format.json { render json: @worker }
end
end
and this is views/tasks/index:
<% @task.each do |task| %>
<tr>
<td><%= task.name %></td>
<td><%= task.task %></td>
<td><%= task.done %></td>
</tr>
<% end %>
In addition, I defined routes.rb:
TODO::Application.routes.draw do
#resources :workers
#root to:"workers#index"
match '/workers/:id/index', :to => 'tasks#index', :as => 'index_task'
resources :workers do
resources :tasks
end
I think I didn’t define the routes.rb correctly, because my error is:
Routing Error
No route matches {:action=>"show", :controller=>"tasks", :worker_id=>"alon"}
Try running rake routes for more information on available routes.
First, you could simplify your routes by removing the unnecessary
matchdirective. By declaring :you nested the tasks resources into the workers ones. Your tasks index will then be accessible using :
where
idis the primary key of your worker model.Rails path helpers are sensitive to the singular / plural form. The path in the
link_tocall corresponds to a specific worker (singular) containing a list of tasks (plural). Rails router expects a primary key or a model instance as the id parameter :