2012-07-29 127 views
0

我有一个Rails应用程序,它有一个Employee模型,一个Skill模型和一个Department模型。使用Rails自己的嵌套资源

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 

不过,我也希望能够独立创造技能和部门。我只需要能够将一个部门和一项技能“挂钩”给一名员工。该路线,这样,道理(/员工/:ID /技能/员工/:ID /部),但就像我说的,我希望能够做到

/departments 
/skills 
/skills/new 

等。

我能做

EmployeeList::Application.routes.draw do 

    resources :departments 
    resources :skills 

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

,这为我提供了我想要的路线,但它看起来就像在我的routes.rb文件列出了两次的资源非常糟糕的做法。我应该怎么做?

回答

2

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

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