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

标签 ruby-on-rails ruby activerecord methods find

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

相关文章:

ruby-on-rails - 在Rails(ActiveRecord)中找到第一条记录的最快方法是什么?

mysql - Rails ActiveRecord 加入并包含在同一个查询中?

php - Yii 2,Active Record类保存后未获取ID

ruby-on-rails - ruby rails : make text field non-editable and display another field while editing a record

ruby-on-rails - 在 :through association 中过滤查询

ruby - 加快我的词法分析算法

ruby - YARD 和 RDoc 不一样?

ruby-on-rails - 在数据库列中存储逗号分隔的列表,如何获取和设置?

ruby-on-rails - 在单个页面上显示多个 View 文件-Rails

ruby - 如何更改/usr/bin/env?