与两个控制器会话

时间:2012-12-23 15:44:29

标签: ruby-on-rails model-view-controller

我有两个控制器:工人和任务。

views/workers/index包含:

<% @workers.group_by(&:name).each do |name, workers| %>
  <tr>
    <td><%= name %></td>
    <td><%= workers.size %></td>
  </tr>
<% end %>

它向我展示了所有工人及其任务数量。

我想添加另一个&lt; td &gt;名为:“显示所有任务”并显示工人X的所有任务。

为了做到这一点,我想我需要这样的东西:

<td><%= link_to 'show all tasks', worker_task_path(name) %></td>

因此,我有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

这是views/tasks/index

<% @task.each do |task| %>
  <tr>
    <td><%= task.name %></td>
    <td><%= task.task %></td>
    <td><%= task.done %></td>
  </tr>
<% end %>

此外,我定义了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

我认为我没有正确定义routes.rb,因为我的错误是

Routing Error

No route matches {:action=>"show", :controller=>"tasks", :worker_id=>"alon"}
Try running rake routes for more information on available routes.

1 个答案:

答案 0 :(得分:1)

首先,您可以通过删除不必要的match指令来简化路由。通过声明:

resources :workers do
    resources :tasks
end

您将任务资源嵌套到工作者资源中。然后可以使用以下方法访问您的任务索引:

workers/:id/tasks

其中id是工人模型的主键。

Rails路径助手对单数/复数形式敏感。 link_to调用中的路径对应于包含任务列表(复数)的特定工作者(单数)。 Rails路由器期望主键或模型实例作为id参数:

<%= link_to 'All tasks', worker_tasks_path(worker) %>
or
<%= link_to 'All tasks', worker_tasks_path(worker.id) %>