Ruby on rails ActiveRecord扩展模块应该放在哪里?
我有这个模块:Ruby on rails ActiveRecord扩展模块应该放在哪里?,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我有这个模块: class ActiveRecord::Base class << self def has_simple_search(*attrs) raise 'has_simple_search expects at least one attribute' if attrs.empty? instance_eval do # because this is ActiveRecord::Base, the class inherits this
class ActiveRecord::Base
class << self
def has_simple_search(*attrs)
raise 'has_simple_search expects at least one attribute' if attrs.empty?
instance_eval do # because this is ActiveRecord::Base, the class inherits this
class_attribute :simple_search_fields
self.simple_search_fields = attrs.flatten
def simple_search(search_string)
return find(:all) if search_string.nil? || search_string.blank?
attrs = self.simple_search_fields
like_s = attrs.map{|f| "#{self.table_name}.#{f.to_s} REGEXP ?"}.join(' OR ')
terms = search_string.split(' ').map{|s| Regexp.escape(s.strip)}
where(Array.new(attrs.count, terms.join('|')).unshift(like_s))
end
end
end
end
end
我试图在我的Rails应用程序中实现这一点,但我找不到应该把它放在哪里
另外:这段代码是否可用于rails 4?您应该将其放入config/initializer中
我真的不知道它是否可以在Rails 4上重用,试试看。我需要在模型中添加一些东西吗?只要我理解Modelsimple\u searchquery在创建初始值设定项后应该可以工作。是吗?是的,你是对的。您所需要的只是一个包含上述确切内容的文件,它应该可以正常工作。如果不兼容,它可能与Rails 4不兼容。对此投反对票的人能否解释一下原因?谢谢。我试过并在初始化器中工作过。但它不是很容易重复使用,我没有投你反对票。投票和评分正确有什么意义?我并不是说它可以工作,而是你说它可能无法重复使用。