加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 3是否嵌套资源?

发布时间:2020-12-17 02:16:57 所属栏目:百科 来源:网络整理
导读:我有一个“公司”,里面有“项目”.随着时间的推移,我们现在需要添加与“项目”相关的“链接”.我的路线目前如下所示: resources :companies do resources :projects do resources :links endend 这似乎是错误的,因为嵌套2层深.如果我像这样嵌套,我现在也不
我有一个“公司”,里面有“项目”.随着时间的推移,我们现在需要添加与“项目”相关的“链接”.我的路线目前如下所示:

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

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

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

这是我的Projects模型和我的Links模型..

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级深度而其他的根本没有嵌套.

那么,最好的方法是什么,以便我可以拥有“链接”和其他与“项目”相关的模型,而“项目”仍然与“公司”相关?

解决方法

您可以使用浅嵌套路由处理它,如下所示:

resources :companies do
  resources :projects
end

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

然后你有像new_company_project_path,new_project_link_path等路线.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读