2012-01-30 154 views
4

我有一个“公司”,其中有“项目”。随着时间的推移,我们现在需要添加与“项目”相关的“链接”。我的路线目前看起来如下:Rails 3嵌套资源与否?

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

这似乎是错误的,因为嵌套2层深。我也不再有new_company_project_path(@company)了,如果我像这样嵌套,现在不允许我为公司创建项目。

我将需要在未来几个月内添加其他模型以与项目相关。

这里是我的项目模型和我的链接模型以及..

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 

这似乎嵌套是不正确的方法。如果嵌套不是正确的方法,那么人们如何去拯救这种关联?例如,在我目前的控制器我做这个救我的嵌套对象:

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 

我无法找到关于这个问题太多信息,我阅读使用前嵌套的路线只有1级深,别人不要的书一点都不窝。

那么,做到这一点的最好方法是什么,以便我可以在与“公司”有关的“项目”中保留与“项目”相关的“链接”和其他模型?

回答

3

你可以用浅嵌套的路线这样的处理:

resources :companies do 
    resources :projects 
end 

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

然后你有一个像new_company_project_path,new_project_link_path路线,等等。

0

嵌套路线和“嵌套”模型是两个不同的东西。

嵌套你的模型,你现在做的方式现在似乎没问题。

至于路线,考虑邀请他们shallow,为解释herehere