Ruby on Rails:嵌套命名范围
有没有办法将不同模型的命名范围嵌套在一起?
示例:
class Company
has_many :employees
named_scope :with_employees, :include => :employees
end
class Employee
belongs_to :company
belongs_to :spouse
named_scope :with_spouse, :include => :spouse
end
class Spouse
has_one :employee
end
有什么好方法让我找到一家公司,同时包括员工和配偶,如下所示:Company.with_employees.with_spouse.find(1)
或者我是否有必要在公司中定义另一个named_scope::with_employees_and_spouse, :include =>; {:员工=> :spouse}
在这个人为的示例中,这还不错,但是我的应用程序中的嵌套更深,如果我不必添加在每个位置重新定义包含的非 DRY 代码,我会喜欢它嵌套的级别。
Is there any way to nest named scopes inside of each other from different models?
Example:
class Company
has_many :employees
named_scope :with_employees, :include => :employees
end
class Employee
belongs_to :company
belongs_to :spouse
named_scope :with_spouse, :include => :spouse
end
class Spouse
has_one :employee
end
Is there any nice way for me to find a company while including employees and spouses like this:Company.with_employees.with_spouse.find(1)
or is it necessary for me to define another named_scope in Company::with_employees_and_spouse, :include => {:employees => :spouse}
In this contrived example, it's not too bad, but the nesting is much deeper in my application, and I'd like it if I didn't have to add un-DRY code redefining the include at each level of the nesting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用默认范围,
然后这应该可以工作。不过我还没有测试过。
You can use default scoping
Then this should work. I have not tested it though.
您需要始终定义所有条件。但是你可以定义一些方法来组合一些named_scope
You need define all the time all of your conditions. But you can define some method to combine some named_scope
试试这个
try this