gpt4 book ai didi

ruby-on-rails - Ruby 通过自定义方法找到?

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:57 24 4
gpt4 key购买 nike

我正在尝试找出一种通过混合自定义方法的常用 Rails 3.0 语法来搜索 ActiveRecord 模型的方法。

例如:

class User < ActiveRecord::Base
def custom_method
if [...]
return true
else
return false
end
end
end

我想以这种方式使用 ActiveRecord 调用它:

User.find(:all).where(custom_method is true)

有什么方法可以解决这个问题?如果语法对我要传达的内容不准确,我们深表歉意。

编辑:我想澄清一下,使用的custom_method 相当复杂,因此最好调用它而不是将其转换为 sql 语法。

最佳答案

这通常是用作用域或类方法实现的

class User < ActiveRecord::Base
scope :active, -> { where(status: 'active') }

def self.hidden
where(status: 'hidden')
end
end

# Both a scope and class method are then used the the same way
User.active # User.where(status: 'active')

User.where(foo: 'bar').active # User.where(foo: 'bar', status: 'active')
User.where(foo: 'bar').hidden # User.where(foo: 'bar', status: 'hidden')

如果 custom_method 过于复杂或依赖于未存储在数据库中的属性,您可能需要求助于过滤内存中的项目。

User.where(foo: 'bar').to_a.select(&:custom_method)

关于ruby-on-rails - Ruby 通过自定义方法找到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24566860/

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