我正在建立一个网络应用程序,其中有多个项目。一般的数据模型是这样的,每个项目都有许多资源,如文档、注册表、etc.Something,这些资源包括:
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/D操作都将通过命名空间完成。但是,当用户查看项目时,我希望路由中的project_id:
‘0.0.0.0:3000/:project_id/document/
或
'0.0.0.0:3000/:project_id/register/1/new我是这样想的:
match '/:project_id/:controller/:id'我假设我要将project_id存储在会话中?如果我为了一些更简单的东西而放弃这些路线,比如:
"0.0.0.0:3000/documents"然后如何将任何CRUD操作绑定到文档或注册到当前项目?当然,我不需要将其硬连接到每个控制器中?
帮助!
发布于 2011-02-02 03:09:37
我想你需要的是嵌套的资源。
resources :projects do
resources :documents
resources :registers
end现在你会得到这样的路由:
/projects/:project_id/documents
/projects/:project_id/registers您将能够在DocumentsController和RegistersController中调用params[:project_id]。您不需要使用会话来存储project_id。这将在url内提供给您。在创建RESTful应用程序时,应尽可能避免使用会话。
您需要做的唯一额外的事情就是在两个控制器的create操作中设置关系:
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现在,您可以在create操作中执行以下操作:
def create
@document = Document.new(params[:document])
@document.project = current_project
# Now you save the document.
end您还可以在寄存器和文档的视图中调用current_project。希望这对你有帮助!
有关嵌套资源的更多信息,请查看Ruby on Rails指南:http://edgeguides.rubyonrails.org/routing.html#nested-resources
https://stackoverflow.com/questions/4858126
复制相似问题