Ruby on rails rails应用程序中的正确路由配置

Ruby on rails rails应用程序中的正确路由配置,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,我用CRUD方法创建了两个具有相应控制器的表。这是我在routes.rb中的内容: resources :employees resources :tasks 现在,我希望能够将任务分配/取消分配给员工(员工和任务之间存在许多与manny的关联)。将资源:员工嵌套在资源:任务中可以吗 所以我的路线。rb会 resources :employees resources :tasks resources :tasks do resources :employee end

我用CRUD方法创建了两个具有相应控制器的表。这是我在routes.rb中的内容:

 resources :employees

 resources :tasks
现在,我希望能够将任务分配/取消分配给员工(员工和任务之间存在许多与manny的关联)。将资源:员工嵌套在资源:任务中可以吗 所以我的路线。rb会

resources :employees
  resources :tasks

  resources :tasks do
  resources :employee
   end 

如果可以使用的话,我是否需要为我想要用来为员工分配任务的方法创建一个不同的控制器。类似于employeetask控制器。

您应该查看rails指南的嵌套资源部分:

他们举的例子是:

class Magazine < ApplicationRecord
  has_many :ads
end

class Ad < ApplicationRecord
  belongs_to :magazine
end
由此产生:

HTTP Verb   Path    Controller#Action   Used for
GET /magazines/:magazine_id/ads ads#index   display a list of all ads for a specific magazine
GET /magazines/:magazine_id/ads/new ads#new return an HTML form for creating a new ad belonging to a specific magazine
POST    /magazines/:magazine_id/ads ads#create  create a new ad belonging to a specific magazine
GET /magazines/:magazine_id/ads/:id ads#show    display a specific ad belonging to a specific magazine
GET /magazines/:magazine_id/ads/:id/edit    ads#edit    return an HTML form for editing an ad belonging to a specific magazine
PATCH/PUT   /magazines/:magazine_id/ads/:id ads#update  update a specific ad belonging to a specific magazine
DELETE  /magazines/:magazine_id/ads/:id ads#destroy delete a specific ad belonging to a specific magazine
如果您想设置一个特殊的控制器来处理关系,那么在您的情况下,您可以执行以下操作:

...
...

resources :tasks do
  resources :employee, controller: 'task_employees'
end 

我建议你:

resources :employees do 
  resources :tasks, only: [:index, :new, :create]
end

resources :tasks do
  resources :employees, only: [:index, :new, :create]
end
这将为您提供(在控制台中运行
rake routes
):

如您所见,您只需要
任务控制器
员工控制器
。您不需要任何其他控制器

请注意,在
TasksController
新建
操作中,您可能有一个
:employee_id
参数,也可能没有,如上面两个路由声明所示:

new_employee_task GET    /employees/:employee_id/tasks/new(.:format)    tasks#new
         new_task GET    /tasks/new(.:format)                           tasks#new
因此,您可能需要执行以下操作:

class TasksController < ApplicationController

  def new
    if @employee = Employee.find_by(id: params[:employee_id])
      @task = @employee.tasks.build(task_params)
    else
      @task = Task.new(task_params)
    end
    ...
  end

end
class TasksController
您需要为
索引
创建
操作执行类似的操作。而且,对于
索引
创建
新建
操作,您可能希望在
员工控制器
中执行类似的操作

new_employee_task GET    /employees/:employee_id/tasks/new(.:format)    tasks#new
         new_task GET    /tasks/new(.:format)                           tasks#new
class TasksController < ApplicationController

  def new
    if @employee = Employee.find_by(id: params[:employee_id])
      @task = @employee.tasks.build(task_params)
    else
      @task = Task.new(task_params)
    end
    ...
  end

end