Rails 3 nested resources or not?

I have a "Company" in which there are "Projects". Over time, we need to add “Links” related to “Projects”. My routes currently look like this:

resources :companies do resources :projects do resources :links end end 

This seems wrong due to the deep nesting of 2 levels. I also no longer have new_company_project_path(@company) if I also have a jack that now denies that I have ever created projects for a company.

I will need to add other models that will be associated with projects in the coming months.

Here is my project model and my link model.

 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 that nesting is not correct. If nesting is not proper, how can you keep 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 cannot find too much information about this topic and the books I read before using nesting routes with only 1 depth level, while others do not nest at all.

So, what is the best way to do this so that I have “links” and other models related to “projects”, while “Projects” remain connected to “companies”?

+4
source share
2 answers

You can handle it using shallow nested routes, for example:

 resources :companies do resources :projects end resources :projects do resources :links resources :sausages resources :patties end 

Then you have routes like new_company_project_path, new_project_link_path, etc.

+3
source

Nested routes and nested models are two different things.

Nesting your models the way you do it now seems to be all right.

Regarding routes, consider making them shallow , as described here and here.

0
source

Source: https://habr.com/ru/post/1393838/


All Articles