Rails控制器查找器模式以干燥帐户过滤器

时间:2012-07-08 18:07:39

标签: ruby-on-rails activerecord controller dry

我的控制器中有如下代码。这是为特定帐户过滤模型(用于多租户)。有没有简单的方法来干这个? current_account_id是控制器助手方法,取决于当前用户。

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

不确定在Application Controller中添加辅助方法是否是最好的方法。

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

def job_with_current_account
  Job.with_account(current_account_id)
end

然后在控制器中的任何地方使用此方法,例如

job_with_current_account.active.....

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

1 个答案:

答案 0 :(得分:2)

如果你已经在两个方向上定义了关联,并且假设你有一个current_account帮助器,那么你可以改用它:

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

它更简洁,您无需在所有模型中定义with_account范围。