【问题标题】:Use Rails nested resources on their own单独使用 Rails 嵌套资源
【发布时间】:2012-07-29 19:44:32
【问题描述】:

我有一个 Rails 应用程序,它有一个 Employee 模型、一个 Skill 模型和一个 Department 模型。

class Employee < ActiveRecord::Base
  belongs_to :department
  has_and_belongs_to_many :skills
  attr_accessible :email, :firstname, :name, :twitter
end

class Skill < ActiveRecord::Base
  has_and_belongs_to_many :employees
  attr_accessible :name
end

class Department < ActiveRecord::Base
  attr_accessible :name
end

我试图为此写下路线,但这就是我遇到麻烦的地方。

我认为这样做是有意义的

resources :employees do
  resource :department
  resources :skills
end

但是,我也希望能够独立创建技能和部门。我只需要能够将部门和技能“联系”到员工身上。像这样的路线是有意义的(/employees/:id/skills、/employees/:id/department),但就像我说的,我希望能够做到

/departments
/skills
/skills/new

等等。

我可以的

EmployeeList::Application.routes.draw do

  resources :departments
  resources :skills

  resources :employees do
    resource :department
    resources :skills
  end
end

这为我提供了我想要的路线,但在我的 routes.rb 文件中列出两次资源看起来真的很糟糕。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails routes nested


    【解决方案1】:

    如果,正如您所写的“我还希望能够独立创建技能和部门。我只需要能够将部门和技能‘连接’到员工。”那么这显然不是嵌套资源imho的情况。嵌套资源只能存在于其“周围”资源的“内部”。与 belongs_to 和 has_many 的简单 1:n 关系应该是您想要的,因此在 routes.rb 中:

    EmployeeList::Application.routes.draw do
      resources :departments
      resources :skills
      resources :employees
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      相关资源
      最近更新 更多