[英]Use Rails nested resources on their own
I have a Rails application which has an Employee model, a Skill model and a Department model. 我有一个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
I was trying to write down the routes for this, but this is where I run into trouble. 我试图写下这条路线,但这是我遇到麻烦的地方。
I think it makes sense to do 我觉得这样做很有意义
resources :employees do
resource :department
resources :skills
end
however, I also want to be able to create skills and departments independently. 但是,我也希望能够独立创建技能和部门。 I only need to be able to 'hook up' a department and a skill to an employee.
我只需要能够将部门和技能“挂钩”给员工。 The routes, like this, make sense (/employees/:id/skills, /employees/:id/department), but like I said, I would like to be able to do
像这样的路线是有意义的(/ employees /:id / skills,/ employees /:id / department),但就像我说的,我希望能够做到
/departments
/skills
/skills/new
etc.. 等等..
I could do 我可以做
EmployeeList::Application.routes.draw do
resources :departments
resources :skills
resources :employees do
resource :department
resources :skills
end
end
and this provides me with the routes I want, but it looks like really bad practice having the resources listed twice in my routes.rb file. 这为我提供了我想要的路线,但在我的routes.rb文件中列出两次资源看起来真的很糟糕。 How should I do this?
我该怎么做?
if, as you wrote "I also want to be able to create skills and departments independently. I only need to be able to 'hook up' a department and a skill to an employee." 如果,正如你写的那样“我也希望能够独立地创造技能和部门。我只需要能够'把一个部门和一个技能挂钩'给员工。” then this is clearly not a case for nested resources imho.
那么这显然不是嵌套资源imho的情况。 Nested Resources can only exist "within" their "surrounding" resource.
嵌套资源只能存在于“周围”资源“内”。 A simple 1:n relation with belongs_to and has_many should be what you want, thus in routes.rb:
与belongs_to和has_many的简单1:n关系应该是你想要的,因此在routes.rb中:
EmployeeList::Application.routes.draw do
resources :departments
resources :skills
resources :employees
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.