我正在尝试找出一种通过混合自定义方法的常用 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/