我有一个名为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
如果我尝试从user_controller访问此类,则会出错。 我试图使用的代码是:
if (@User.save)
guid = Action.inspect()
guid = Action.register_action(@User.email,"REGISTER")
MemberMailer.deliver_confirmation(@User,guid)
end
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'
我做错了什么?
我是Rails的新手,所以道歉是愚蠢的。
答案 0 :(得分:6)
问题出在这一行:
guid = Action.register_action(@User.email,"REGISTER")
register_action
是一个实例方法,而不是类方法,所以你在Action
类的实例上调用它,而不是Action
类本身
如果你想将register_action
定义为类方法,你应该这样做:
def self.register_action(email, type)
# ... Body ...
end
答案 1 :(得分:2)
更改
def register_action(email,type)
到
def self.register_action(email,type)
或
def Action.register_action(email,type)
答案 2 :(得分:0)
在register_action
方法中,您需要@action = Action.new
而不是@action = new()
。或者,您可以像这样构建它:
@action = Action.new(:guid => "123456789", :email => email, :action => type)
此外,您已在register_action
类中将Action
定义为实例方法,但您使用Action.register_action
将其称为类方法。将其更改为:
def self.register_action(email, type)
...
end