I have a “Company” which has “Projects” within them. As time goes on we now need to add “Links” that are related to “Projects”. My routes currently look like the following:
resources :companies do
resources :projects do
resources :links
end
end
This seems wrong due to the nesting 2 levels deep. I also no longer have new_company_project_path(@company) anymore if I nest like this which now denies me to ever creating projects for a company.
I will need to add other models to relate to Projects in the coming months.
Here is my Projects model and my Links model as well..
class Link < ActiveRecord::Base
attr_accessible :link_name, :url, :description
belongs_to :project
end
class Project < ActiveRecord::Base
belongs_to :company
belongs_to :user
validates :title, :presence => true
validates :description, :presence => true,
:length => { :minimum => 10 }
end
It would seem nesting is not the proper way. If nesting is not the proper way, how does one go about saving the association? For example, in my current controller I save my nested objects by doing this:
class ProjectsController < ApplicationController
before_filter :authenticate_user!
before_filter :find_company
def new
@project = @company.projects.build
end
def create
@project = @company.projects.build(params[:project])
if @project.save
flash[:notice] = "Project has been created."
redirect_to [@company, @project]
else
flash[:alert] = "Project has not been created."
render :action => "new"
end
end
private
def find_company
@company = Company.find(params[:company_id])
end
end
I can’t find too much info on this subject and the books I read before used nesting routes only 1 level deep and others don’t nest at all.
So, what is the best way to do this so that I can have “Links” and other models related to “Projects” while “Projects” remain related to “Companies”?
You can handle it with shallow nested routes like this:
Then you have routes like new_company_project_path, new_project_link_path, etc.