实施帐户范围

时间:2011-01-06 10:37:28

标签: ruby-on-rails ruby-on-rails-3 routes

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

 scope ":account_id" do
   resources :projects
   ...
 end

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

  project_path(current_account, project)

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

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

2 个答案:

答案 0 :(得分: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

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

project_path(project)

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

project_path(project, :account_id => other_account)

请注意,这在控制台中无效。

答案 1 :(得分:1)

从Rails 3.0开始,使用url_options操作url params更简单:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def url_options
    { account_id: current_account.id  }.merge(super)
  end
end