在Rails中,我在新模型中调用函数时遇到NoMethodError

sea*_*boy 2 ruby-on-rails

我有一个名为Action的模型.它看起来像这样:

class Action < ActiveRecord::Base
  def register_action(email,type)
    @action = new()
    @action.guid = "123456789"
    @action.email = email 
    @action.action = type 

    action.guid if @action.save 
  end
end
Run Code Online (Sandbox Code Playgroud)

如果我尝试从我的user_controller访问这个类,我会收到一个错误.我试图使用的代码是:

if (@User.save)
  guid = Action.inspect() 
  guid = Action.register_action(@User.email,"REGISTER")
  MemberMailer.deliver_confirmation(@User,guid)
end
Run Code Online (Sandbox Code Playgroud)

Action.inspect()工作正常,所以我猜测可以看到Action类,但调用register_action的行返回以下错误:

NoMethodError in UserController#createnew
undefined method `register_action' for #<Class:0x9463a10>
c:/Ruby187/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1994:in `method_missing'
E:/Rails_apps/myapp/app/controllers/user_controller.rb:32:in `createnew'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

我是Rails的新手,所以对于愚蠢而道歉.

mip*_*adi 6

问题出在这一行:

guid = Action.register_action(@User.email,"REGISTER")
Run Code Online (Sandbox Code Playgroud)

register_action是一个实例方法,而不是类方法,所以你在类的实例上调用它Action,而不是Action类本身.

如果要将其定义register_action为类方法,则应该这样做:

def self.register_action(email, type)
  # ... Body ...
end
Run Code Online (Sandbox Code Playgroud)