有没有办法将命名范围组合成一个新的命名范围? [英] Is there a way to combine named scopes into a new named scope?

查看:41
本文介绍了有没有办法将命名范围组合成一个新的命名范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

class Foo { :a =>一种 } }named_scope :b, lambda { |b|:条件=>{:b =>乙 } }结尾

我愿意

class Foo { :a =>a, :b =>乙 } }结尾

但我更愿意以干燥的方式进行.我可以通过使用获得相同的效果

 Foo.a(something).b(something_else)

但它不是特别可爱.

解决方案

好吧,我还是 Rails 的新手,我不确定您在这里要做什么,但如果您只是要代码重用为什么不使用常规的类方法?<预><代码>def self.ab(a, b)a(a).b(b)结尾

您可以通过使用 *args 而不是 a 和 b 来使其更加灵活,然后可能使其中一个成为可选.如果您坚持使用named_scope,您不能扩展它来做同样的事情吗?

如果我对您想要做的事情完全不了解,请告诉我.

I have

class Foo < ActiveRecord::Base
  named_scope :a, lambda { |a| :conditions => { :a => a } }
  named_scope :b, lambda { |b| :conditions => { :b => b } }
end

I'd like

class Foo < ActiveRecord::Base
  named_scope :ab, lambda { |a,b| :conditions => { :a => a, :b => b } }
end

but I'd prefer to do it in a DRY fashion. I can get the same effect by using

 Foo.a(something).b(something_else)

but it's not particularly lovely.

解决方案

Well I'm still new to rails and I'm not sure exactly what you're going for here, but if you're just going for code reuse why not use a regular class method?


        def self.ab(a, b)
            a(a).b(b)
        end
    

You could make that more flexible by taking *args instead of a and b, and then possibly make one or the other optional. If you're stuck on named_scope, can't you extend it to do much the same thing?

Let me know if I'm totally off base with what you're wanting to do.

这篇关于有没有办法将命名范围组合成一个新的命名范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆