如何在ruby-on-rails的模型类方法中调用辅助方法?

2026-04-11 15:221阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计237个文字,预计阅读时间需要1分钟。

如何在ruby-on-rails的模型类方法中调用辅助方法?

我创建了一个辅助方法,希望在模型类方法上运行并获取一个找不到方法的错误。+LIB +/model_helper module ModelHelper def method_i_want_to_use puts I want to use this method end end 模型/富 class Foo 我创建了一个帮助方法,我想在模型类方法上运行并获取一个找不到方法的错误.

LIB / model_helper

module ModelHelper def method_i_want_to_use puts "I want to use this method" end end

模型/富

class Foo < ActiveRecord::Base include ModelHelper def self.bar method_i_want_to_use end end

此设置为我提供了无方法错误.

您必须扩展模块而不是包含.

extend ModelHelper

include使方法可用作Foo的实例方法.这意味着,您可以在Foo的实例上调用方法method_i_want_to_use,而不是在Foo本身上调用.如果你想调用Foo本身,那么使用extend.

如何在ruby-on-rails的模型类方法中调用辅助方法?

module ModelHelper def method_i_want_to_use puts "I want to use this method" end end class Foo extend ModelHelper def self.bar method_i_want_to_use end end Foo.bar # >> I want to use this method

本文共计237个文字,预计阅读时间需要1分钟。

如何在ruby-on-rails的模型类方法中调用辅助方法?

我创建了一个辅助方法,希望在模型类方法上运行并获取一个找不到方法的错误。+LIB +/model_helper module ModelHelper def method_i_want_to_use puts I want to use this method end end 模型/富 class Foo 我创建了一个帮助方法,我想在模型类方法上运行并获取一个找不到方法的错误.

LIB / model_helper

module ModelHelper def method_i_want_to_use puts "I want to use this method" end end

模型/富

class Foo < ActiveRecord::Base include ModelHelper def self.bar method_i_want_to_use end end

此设置为我提供了无方法错误.

您必须扩展模块而不是包含.

extend ModelHelper

include使方法可用作Foo的实例方法.这意味着,您可以在Foo的实例上调用方法method_i_want_to_use,而不是在Foo本身上调用.如果你想调用Foo本身,那么使用extend.

如何在ruby-on-rails的模型类方法中调用辅助方法?

module ModelHelper def method_i_want_to_use puts "I want to use this method" end end class Foo extend ModelHelper def self.bar method_i_want_to_use end end Foo.bar # >> I want to use this method