I have a Rails application which has an Employee model, a Skill model and a Department model.
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
/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. 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. 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: