Rails:模型中的调用方法

mic*_*key 6 ruby model ruby-on-rails

无法想出这个.在rails模型中,我想调用同一模型中的方法来操作find方法返回的数据.这个'filter'方法将从这个模型中的许多自定义find方法调用,所以我希望它是分开的.(我无法从SQL中过滤它太复杂了)

这是一个例子:

#controller
@data = Model.find_current

#model
class Model
  def self.find_current
    @rows = find(:all)
    filter_my_rows
    return @rows
  end

  def filter_my_rows
    #do stuff here on @rows
    for row in @rows
      #basically I remove rows that do not meet certain conditions
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

结果是:未定义的方法`filter_my_rows'

感谢您的任何帮助!

tad*_*man 4

部分问题是您正在定义一个名为 find_current 的类方法和一个名为 filter_my_rows 的实例方法。通常,您将它们定义在相同的范围内,以便它们一起工作。

另一件事是,您可以通过简单的 Array#reject 调用来完成所需的大量过滤。例如:

@models = all.reject do |m|
   # This block is used to remove entries that do not qualify
   # by having this evaluate to true.
   !m.current
end
Run Code Online (Sandbox Code Playgroud)

您也可以通过根据需要插入函数来对其进行模块化,但如果您不小心的话,管理起来可能会变得非常复杂。

# Define reusable blocks that are organized into a Hash
CONDITION_FILTERS = {
  :current => lambda { |m| m.current }
}

# Array#select is the inverse of Array#reject
@models = all.select(CONDITION_FILTERS[:current])
Run Code Online (Sandbox Code Playgroud)

虽然您在问题中指出,这只是因为担心在从数据库加载所有记录之前无法确定特定记录的相关性而需要这样做,但这通常是不好的形式,因为您可能会拒绝大量记录您费尽心思检索并实例化为模型的数据,结果却立即将其丢弃。

如果可能的话,您至少应该在请求期间缓存检索到的行,这样您就不必一遍又一遍地获取它们。