如何重用命名范围?

发布于 2024-08-08 12:12:24 字数 367 浏览 3 评论 0原文

您好,我的 User 模型中有一个 named_scope ,如下所示。

named_scope :by_gender, lamdba { |gender| { :conditions => { :gender => gender } } }

我想创建另外两个命名范围,它们重新使用这个范围,例如,

named_scope :male,   lambda { by_gender('male') }
named_scope :female, lambda { by_gender('female') }

知道该怎么做吗?

Hi I have a named_scope in my User model as following.

named_scope :by_gender, lamdba { |gender| { :conditions => { :gender => gender } } }

I want to create other two named scopes which re use this one something like,

named_scope :male,   lambda { by_gender('male') }
named_scope :female, lambda { by_gender('female') }

Any idea what to do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海里的那抹蓝 2024-08-15 12:12:25

您可以提供执行硬连线参数传递的类方法:

def self.male
    by_gender('male')
end

def self.female
    by_gender('female')
end

或者,由于您使用的named_scope非常简单,您可以删除by_gender范围并简单地使用:

named_scope :male, :conditions => {:gender => 'male'}
named_scope :female, :conditions => {:gender => 'female'}

第二个选项当然是有条件的,您实际上并不明确需要by_gender范围其他任何地方。

You could provide class methods that perform the hardwired argument passing:

def self.male
    by_gender('male')
end

def self.female
    by_gender('female')
end

or, as the named_scope you are using is so simple you could cut out the by_gender scope and simply use:

named_scope :male, :conditions => {:gender => 'male'}
named_scope :female, :conditions => {:gender => 'female'}

The second option is of course conditional on you not actually requiring the by_gender scope explicitly anywhere else.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文