gpt4 book ai didi

ruby-on-rails - 帮我重构 ruby​​ 下一段代码

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:52 24 4
gpt4 key购买 nike

@people = People.scoped
@people = @people.where(...) if ...
@people = @people.where(...) if ...
@people = @people.where(...) if ...
@people = @people.where(...) if ...

有没有 ruby 现有的解决方案来制作类似的东西

@people = People.scoped

@people.???? do
where(...) if ...
where(...) if ...
where(...) if ...
end

PS:感谢解答。但是您提供的解决方案看起来像

def self.conditional_scope
where(...) if ...
where(...) if ...
where(...) if ...
end

我认为即使所有“如果”都为真,我也只会排在最后。

我说的对吗?

最佳答案

我认为您应该熟悉 named_scopes: http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html

它们是可组合的,所以你可以这样写:

People.tall.having_children.older_than(30)

其中“tall”、“having_children”和“older_than”是命名范围。

关于ruby-on-rails - 帮我重构 ruby​​ 下一段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7011631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com