实施帐户范围

Rya*_*igg 12 routes ruby-on-rails ruby-on-rails-3

目前在我的应用程序中,我有项目和用户的概念.现在我想为这些实现一个帐户范围,以便项目和用户都属于一个帐户,而不是特别没有.通过这样做,我想像我这样的范围:

 scope ":account_id" do
   resources :projects
   ...
 end
Run Code Online (Sandbox Code Playgroud)

但是,通过scope使用命名参数实现路由,这会更改路由助手的执行方式,以便project_path路由助手现在需要两个参数,一个用于account_id参数,另一个用于id参数,如下所示:

  project_path(current_account, project)
Run Code Online (Sandbox Code Playgroud)

这个微小的 scope变化要求我在控制器和视图中对应用程序进行大量更改,以便我使用这些路径助手.

当然,当然,有一个干净的方法可以做到这一点,而无需更改应用程序中的每个路由助手?

小智 13

使用default_url_options哈希为:account_id添加默认值:

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :set_default_account_id

  def set_default_account_id
    self.default_url_options[:account_id] = current_account
  end
end
Run Code Online (Sandbox Code Playgroud)

然后,您可以将url helper与单个参数一起使用:

project_path(project)
Run Code Online (Sandbox Code Playgroud)

您可以通过将:account_id作为哈希参数传递给路径来在视图中覆盖它:

project_path(project, :account_id => other_account)
Run Code Online (Sandbox Code Playgroud)

请注意,这在控制台中不起作用.