【问题标题】:Rails controller finder pattern to dry up an account filterRails 控制器查找器模式来干掉帐户过滤器
【发布时间】:2012-07-08 18:07:38
【问题描述】:

我的控制器中都有如下代码。这是为了过滤特定帐户的模型(用于多租户)。有没有简单的方法来干燥这个? current_account_id 是一个依赖于当前用户的控制器辅助方法。

Job.with_account(current_account_id).active.......
Contact.with_account(current_account_id).active.......

不确定在应用程序控制器中添加辅助方法是否是最好的方法。

编辑: 为了澄清,我可以使用如下代码:

def job_with_current_account
  Job.with_account(current_account_id)
end

然后在控制器的任何地方都使用这个方法,例如

job_with_current_account.active.....

我想知道是否有另一种更优雅的方式来做到这一点。

【问题讨论】:

    标签: ruby-on-rails activerecord controller dry


    【解决方案1】:

    如果您已经定义了两个方向的关联,并假设您有一个 current_account 助手,那么您可以改用它:

    current_account.jobs.active.....
    current_account.contacts.active.....
    

    它更简洁一些,您不需要在所有模型中定义with_account 范围。

    【讨论】:

    • 哇,我怎么会错过这个 :) 实际上我有一个 current_account 助手,所有的关系都连接起来了。感谢您帮助我:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多