【问题标题】:Implementing account scoping实施帐户范围
【发布时间】:2011-01-06 10:37:28
【问题描述】:

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

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

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

  project_path(current_account, project)

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

肯定,肯定,肯定,有一种干净的方法可以做到这一点,而不必更改应用程序中的每个路由助手?

【问题讨论】:

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


    【解决方案1】:

    使用 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 助手:

    project_path(project)
    

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

    project_path(project, :account_id => other_account)
    

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

    【讨论】:

      【解决方案2】:

      从 Rails 3.0 开始,使用 url_options 操作 url 参数变得更加简单:

      class ApplicationController < ActionController::Base
        protect_from_forgery
      
        def url_options
          { account_id: current_account.id  }.merge(super)
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 2020-07-07
        • 2022-11-03
        • 1970-01-01
        • 2012-12-02
        • 1970-01-01
        • 1970-01-01
        • 2017-12-19
        相关资源
        最近更新 更多