ruby-on-rails – 不能在模型中包含模块

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 不能在模型中包含模块前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在用着 @H_403_2@Ruby version 1.8.7 Rails version 3.0.3

我的rails应用程序的每个模型都有一个叫做alive的方法

@H_403_2@def alive where('deleter is null') end

我不想在每个模型中复制这个代码,所以我做了一个/lib/life_control.rb

@H_403_2@module LifeControl def alive where('deleter is null') end def dead where('deleter is not null') end end

在我的模型(例如client.rb)中我写道:

@H_403_2@class Client < ActiveRecord::Base include LifeControl end

在我的config / enviroment.rb中我写了这一行:

@H_403_2@require 'lib/life_control'

但是现在我得到一个没有方法错误

@H_403_2@NoMethodError in ClientsController#index undefined method `alive' for #<Class:0x10339e938> app/controllers/clients_controller.rb:10:in `index'

我究竟做错了什么?

@R_404_323@

include将将这些方法视为实例方法,而不是类方法.你想做的是这样的: @H_403_2@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

这样,活着和死亡将在课堂本身上可用,而不是实例.

原文链接:https://www.f2er.com/ruby/266729.html

猜你在找的Ruby相关文章