2011-02-01 217 views
1

我正在構建一個包含多個項目的Web應用程序。一般的數據模型是這樣的:每個項目都有很多資源,如文件,寄存器,線沿線的etc.Something:Rails 3 - 會話和路由!

class Project < ActiveRecord::Base 
    has_many :documents, :registers, :employments 
    has_many :users, :through => :employments 

class User < ActiveRecord::Base 
    has_many :employments 
    has_many :projects, :through => :employments 

class Document < ActiveRecord::Base 
belongs_to :project 

class Register < ActiveRecord::Base 
belongs_to : project 

困難來自具有路由!項目的任何C UD操作都將通過命名空間完成。但是,當用戶查看一個項目,我想在路由PROJECT_ID這樣的:

「0.0.0.0:3000/:project_id/documents/

OR

'0.0.0.0:3000/:project_id/register/1/new 

我想大概是這樣的:

match '/:project_id/:controller/:id' 

我想我是將project_id存儲在會話中?如果我放棄這些路線的東西simplier如剛:

"0.0.0.0:3000/documents" 

我怎麼那麼綁定任何CRUD行動,以文件或登記,目前該項目?當然,我不必把它連接到每個控制器上?

幫助!

回答

0

我想你需要的是嵌套的資源。

resources :projects do 
    resources :documents 
    resources :registers 
end 

現在你會得到路由是這樣的:

/projects/:project_id/documents 
/projects/:project_id/registers 

您可以撥打params[:project_id]的DocumentsController和RegistersController內。您不需要會話來存儲project_id。這將在網址中提供給你。創建RESTful應用程序時,應儘可能避免會話。

你需要做的是設置兩個控制器的創建行動中關係的唯一的額外的事情:

def create 
    @document = Document.new(params[:document]) 
    @document.project_id = params[:project_id] 
    # Now you save the document. 
end 

我喜歡做的是創造獲取當前項目的ApplicationController內一個輔助方法。

class ApplicationController < ActionController::Base 
    helper_method :current_project 

    private 

    def current_project 
    @current_project ||= Project.find(params[:project_id]) if params[:project_id].present? 
    end 
end 

現在你能做的創建操作中執行以下操作:

def create 
    @document = Document.new(params[:document]) 
    @document.project = current_project 
    # Now you save the document. 
end 

您也可以打電話給current_project你的意見對內部寄存器和文檔。希望能幫助你!

檢查on Rails的Ruby的指導一些更多的信息,嵌套資源:http://edgeguides.rubyonrails.org/routing.html#nested-resources

+0

這聽起來不錯 - 我已經開始使用會話爭取解決工作,但現在我開始認真第二猜測。爲了避免沉重的嵌套,我假設我然後開始淺層嵌套我的資源?即。對於文檔修訂,文檔類型等。 – 2011-02-03 12:20:31