use*_*302 2 ruby methods activerecord ruby-on-rails find
我试图找出一种方法,通过将ActiveRecord模型与常规方法混合使用的常规rails 3.0语法进行搜索。
例如:
class User < ActiveRecord::Base
def custom_method
if [...]
return true
else
return false
end
end
end
Run Code Online (Sandbox Code Playgroud)
并且我想以这种方式使用ActiveRecord来激活它:
User.find(:all).where(custom_method is true)
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?抱歉,如果语法与我要传达的内容不正确。
编辑:我想澄清一下,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')
Run Code Online (Sandbox Code Playgroud)
如果custom_method太复杂或依赖未存储在数据库中的属性,则可能需要诉诸于过滤内存中的项目。
User.where(foo: 'bar').to_a.select(&:custom_method)
Run Code Online (Sandbox Code Playgroud)