实现一个ActiveRecord before_find [英] Implementing an ActiveRecord before_find

查看:94
本文介绍了实现一个ActiveRecord before_find的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立与缓存在一个表中的关键字的搜索。前一用户输入的关键字查找表中,这是归一化的。例如,一些标点符号像' - '是去除与壳体是标准化的。归一化的关键字,然后用于找到获取搜索结果。

I am building a search with the keywords cached in a table. Before a user-inputted keyword is looked up in the table, it is normalized. For example, some punctuation like '-' is removed and the casing is standardized. The normalized keyword is then used to find fetch the search results.

我目前正在处理同一个的before_filter控制器正常化。我想知道是否有办法做到这一点模型代替。概念上的东西就像一个before_find回调将工作虽然那是没有意义的一个实例级别。

I am currently handling the normalization in the controller with a before_filter. I was wondering if there was a way to do this in the model instead. Something conceptually like a "before_find" callback would work although that wouldn't make sense on for an instance level.

推荐答案

您应该使用命名范围:

class Whatever < ActiveRecord::Base

  named_scope :search, lambda {|*keywords|
    {:conditions => {:keyword => normalize_keywords(keywords)}}}

  def self.normalize_keywords(keywords)
    # Work your magic here
  end

end

使用命名范围将让您链其他领域,并且是​​真正的方式使用Rails 3去了。

Using named scopes will allow you to chain with other scopes, and is really the way to go using Rails 3.

这篇关于实现一个ActiveRecord before_find的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆