不能在模型中包含模块 [英] Cannot include module in model
本文介绍了不能在模型中包含模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用
Ruby version 1.8.7
Rails version 3.0.3
我的 rails 应用程序的每个模型中都有一个名为 alive 的方法:
I have a method called alive in every model of my rails app:
def alive
where('deleter is null')
end
我不想在每个模型中都复制这段代码,所以我做了一个/lib/life_control.rb
I don't want to copy this code in every model so I made a /lib/life_control.rb
module LifeControl
def alive
where('deleter is null')
end
def dead
where('deleter is not null')
end
end
在我的模型(例如 client.rb)中我写道:
and in my model (for example client.rb) I wrote:
class Client < ActiveRecord::Base
include LifeControl
end
在我的 config/enviroment.rb 中我写了这一行:
and in my config/enviroment.rb I wrote this line:
require 'lib/life_control'
但现在我得到一个无方法错误:
but now I get a no method error:
NoMethodError in
ClientsController#index
undefined method `alive' for
#<Class:0x10339e938>
app/controllers/clients_controller.rb:10:in
`index'
我做错了什么?
推荐答案
include
会将这些方法视为实例方法,而不是类方法.你想要做的是:
include
will treat those methods as instance methods, not class methods. What you want to do is this:
module LifeControl
module ClassMethods
def alive
where('deleter is null')
end
def dead
where('deleter is not null')
end
end
def self.included(receiver)
receiver.extend ClassMethods
end
end
这样,alive
和 dead
将可用于类本身,而不是其实例.
This way, alive
and dead
will be available on the class itself, not instances thereof.
这篇关于不能在模型中包含模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文